cat brain.log | less

Getting it down on `paper`

Python Basics

These examples have been pulled from various sources.

List comprehension:

Create a list from a function and filter:

S = [2*x for x in range(101) if x**2 > 3]

Generator

Define a generator:

from itertools import count
 
def generate_primes(stop_at=0):
    primes = []
    for n in count(2):
        if 0 < stop_at < n:
            return # raises the StopIteration exception
        composite = False
        for p in primes:
            if not n % p:
                composite = True
                break
            elif p**2 > n:
                break
        if not composite:
            primes.append(n)
            yield n

Using a generator:

for i in generate_primes():  # iterate over ALL primes
    if i > 100:
        break
    print i

map (source):

def cube(x): return x*x*x
map(cube, range(1, 11))  # outputs [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
seq = range(8)
def add(x, y): return x+y
map(add, seq, seq)  # outputs [0, 2, 4, 6, 8, 10, 12, 14]

reduce (source):

def add(x,y): return x+y
reduce(add, range(1, 11))  # outputs 55

filter (source):

def f(x): return x % 2 != 0 and x % 3 != 0
filter(f, range(2, 25))  # outputs [5, 7, 11, 13, 17, 19, 23]

iter (source):

for value in sequence:
    print(value)
for key in dictionary:
    value = dictionary[key]
    print(key, value)
for key, value in dictionary.items():
    print(key, value)

range (source):

a = ['Mary', 'had', 'a', 'little', 'lamb']
for i in range(len(a)):
    print i, a[i]

xrange (source):

z = lambda x, h: [sum((x[i - j] if (0 <= i - j < len(x)) else 0) * h[j] \
for j in xrange(len(h))) \
for i in xrange(len(x) + len(h) - 1)]

Decorators:

class C(object):
 
    @staticmethod
    @funcattrs(grammar="'@' dotted_name [ '(' [arglist] ')' ]",
               status="experimental", author="BDFL")
    def longMethodNameForEffect(longArgumentOne=None,
                                longArgumentTwo=42):
        """This method blah, blah.
 
        It supports the following arguments:
        - longArgumentOne -- a string giving ...
        - longArgumentTwo -- a number giving ...
 
        blah, blah.
 
        """
        raise NotYetImplemented

Strategy Pattern:
Example usage:

class Button:
    """A very basic button widget."""
    def __init__(self, submit_func, label):
        self.on_submit = submit_func   # Set the strategy function directly
        self.label = label
 
# Create two instances with different strategies
button1 = Button(sum, "Add 'em")
button2 = Button(lambda nums: " ".join(map(str, nums)), "Join 'em")
 
# Test each button
numbers = range(1, 10)   # A list of numbers 1 through 9
print button1.on_submit(numbers)   # displays "45"
print button2.on_submit(numbers)   # displays "1 2 3 4 5 6 7 8 9"

See documentation for:

This post was inspired by an item on StackOverflow: Python Progression Path from Apprentice to Guru

 

Comments

No comments so far.

(comments are closed)