Python Recipes Flashcards

(11 cards)

1
Q

Implementing priority queue class (push and pop methods)

A

Push:

heapq. heappush(self._queue, (-priority, self._index, item))
self. _index += 1

Pop:

return heapq.heappop(self._queue)[-1]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Mapping keys to multiple values

A

Use defaultdict from collections

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Finding min, max and sorting of dictionary

A
min_price = min( zip( prices.values(), prices.keys() ) )
#min_price is (10.75, 'FB')
prices_sorted = sorted( zip( ... ) )
# prices_sorted is [ (10.75, 'FB'), ... ]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Finding commonalities in dictionaries

A

Keys views support common set operations.

a. keys() & b.keys()
a. keys() - b.keys()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Removing duplicates from a sequence while maintaining order

A

If items are hashable, then

def dedupe (items):
     seen = set()
     for item in items:
         if item not in seen:
             yield item
             seen.add( item)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Determining most frequently occurring items in a sequence

A

Use Counter in collections

word_counter = Counter( words)
top_three = word_counter.most_common(3)

word_counter.update( more_words)

Counters can be added and subtracted as well

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Sorting list of dictionaries by a common key

A

Use itemgetter:

rows_by_uid = sorted(rows, key=itemgetter(‘uid’))

You can also use lambda expression:

rows_by_uid = sorted(rows, key=lambda r: r[‘uid’])

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Sorting objects without native comparison support

A

Attrgetter:

sorted( users, key=attrgetter(‘user_id’)

Can also use lambda expression

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Group by

A

from itertools import groupby

rows.sort(key=itemgetter(‘date’))

for date, items in groupby(rows, key=itemgetter(‘date’)):

!!!Groupby won’t work without sorting it first!!!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Filtering sequence elements

A

List comprehension, Generator expressions

If filtering process is more complicated, then use filter:

def is_int(val):
     try:
          x = int(val)
          return True
     except ValueError:
          return False 

ivals = list( filter( is_int, values))

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Transforming and reducing data

A

Use generator expression arguments:

s = sum(x*x for x in nums)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly