11/29/2018

Python Notes (3) - Beautiful Python Code by Raymond Hettinger

https://www.youtube.com/watch?v=OSGv2VnC0go

Faster and prettier code:

1. Looping backwards
for color in reversed(colors):
    print color

2. Looping over collection and indices
for i, color in enumerate(colors):
    print i, ":", color

3. Zip of 2 lists
for name, color in zip(names, colors):
    print name, ":", color

! zip has higher memory req, prone to cache miss;
! in python 3.x, using izip instead of zip

4. Sorted list
for color in sorted(colors):
for color in sorted(colors, reverse=True):

def compare_length(c1, c2):
    if len(c1) < len(c2): return -1
    if len(c1) > len(c2): return 1
    return 0

for color in sorted(colors, cmp=compare_length):
for color in sorted(colors, key=len):

Looping over a dict with keys and values:
for k,v in d.items():     # req. memory to store list
for k,v in d.iteritems(): # use iterator instead of mem

Counting with dict
d ={}
for color in colors:
    d[color] = d.get(color, 0) + 1

d = defaultdict(int)
for color in colors:
    d[color] += 1

Grouping with dictionaries:
# group the list by length
names = ['Raymond', 'Rachel', 'Matthew', 'Roger', 'Betty']

#old
d = {}
for name in names:
    key = len(name)
    if key not in d:
        d[key] = []
    d[key].append(name)

#1
d = {}
for name in names:
    key = len(name)
    d.setdefault(key, []).append(name)

#2
d = defaultdict(list)
for name in names:
    key = len(name)
    d[key].append(name)

Function calls with keyword arguments
twitter_search('@obama', False, 20, True)

twitter_search('@obama', retweets=False, numtweets=20, 
               popular=True)


Packing/Unpacking = simultaneous state updates
x, y, dx, dy = ( x + dx *t,
                 y + dy *t,
                 influence(m,x,y),
                 influence(m,x,y))

Concatenating strings
', '.join(names)

Updating sequences
names = ['Raymond', 'Rachel', 'Matthew', 'Roger', 'Betty']

del names[0]
names.pop(0)
names.insert(0, 'mark')

#==>
names = deque(['Raymond', 'Rachel', 'Matthew', 'Roger', 'Betty'])

del names[0]
names.popleft()
names.appendleft('mark')

No comments:

Post a Comment