Thursday, January 28, 2010

What should I know in Python?

This was posted on SO (and promptly closed!):

What questions should every good Python developer be able to answer?

Alex Martelli, author of the Python Cookbook and Python guru extraordinaire, gave these four questions:

• how do you sort a list of dicts by the value each has for key 'foo'?

There's a really nice page on sorting here. Recall that the built-in function sorted takes a keyword argument key. I usually define a function to feed to sorted,

>>> L = [{'foo':1}, {'foo':3}, {'foo':10}]
>>> def f(e): return e['foo']
...
>>> sorted(L, key=f)
[{'foo': 1}, {'foo': 3}, {'foo': 10}]

but the cool kids like lambdas:

>>> import operator
>>> sorted(L, key = operator.itemgetter('foo'))
[{'foo': 1}, {'foo': 3}, {'foo': 10}]

sorted also can do reverse:

>>> sorted(L, key=f, reverse=True)
[{'foo': 10}, {'foo': 3}, {'foo': 1}]




• how do you get the highest 10 integers out of a list of a million integers?

The built-in function sort can do this in an instant.

>>> import random
>>> N = int(1E6)
>>> L = [random.choice(xrange(N)) for i in range(N)]
>>> L.sort()
>>> L[-5:]
[999990, 999991, 999992, 999994, 999998]





• how do you sort a list of strings in case-insensitive alphabetical order?

Feed the built-in function str.lower to sort

>>> FH = open('/usr/share/dict/words')
>>> words = FH.read().strip().split('\n')
>>> FH.close()
>>> len(words)
234936
>>> L = [random.choice(words) for i in range(1000)]
>>> L.sort(key=str.lower)
>>> for w in L[10:15]:
... print w
...
adenophthalmia
advenient
Aegisthus
afterpast
afterripening




• given a list of ints, how do you make a string with their str forms separated by spaces?

This one's trivial.

>>> L = range(10)
>>> print ''.join([str(n) for n in L])
0123456789