31. With a predicate
cubes = []
for x in range(100):
if x % 2:
cubes.append(x ** 3)
cubes = map(lambda x: x ** 3,
filter(lambda x: x % 2, range(100)))
cubes = [x ** 3 for x in range(100) if x % 2]
cubes = [x ** 3 for x in range(100)][1::2]
32. Sum of two dice
table = []
for i in range(1, 7):
row = []
for j in range(1, 7):
row.append(i + j)
table.append(row)
[[i + j for i in range(1, 7)]
for j in range(1, 7)]
51. How many 3-letter strings are
alphabetically between 'foo' and 'bar'?
52. A more complicated generator
def alphagen(start, end=None):
s = list(reversed(start))
while end is None or s != list(reversed(end)):
yield ''.join(reversed(s))
if s == list('z' * len(s)):
s = list('a' * (len(s) + 1))
else:
for i, ch in enumerate(s):
if ch is 'z':
s[i] = 'a'
else:
s[i] = chr(ord(ch) + 1)
break
53. Solution
i = 0
for a in alphagen('bar', 'foo'):
i += 1
print i - 1
# Time taken to create generator: .00000596046