Added example solutions to several chapters. Feel free to create a pull request with your answers. Also for the chapters that have no solutions yet :)
This commit is contained in:
@@ -0,0 +1,29 @@
|
||||
# Implement the quicksort algorithm.
|
||||
import random
|
||||
|
||||
# one-liner approach
|
||||
qs = lambda xs: xs if len(xs) <= 1 else qs(
|
||||
[x for x in xs[1:] if x < xs[0]]) + [xs[0]] + qs(
|
||||
[x for x in xs[1:] if x >= xs[0]])
|
||||
|
||||
|
||||
# more verbose approach
|
||||
def quicksort(xs):
|
||||
if len(xs) <= 1:
|
||||
return xs
|
||||
else:
|
||||
left = quicksort([x for x in xs[1:] if x < xs[0]])
|
||||
right = quicksort([x for x in xs[1:] if x >= xs[0]])
|
||||
middle = [xs[0]]
|
||||
return left + middle + right
|
||||
|
||||
|
||||
def main():
|
||||
# test
|
||||
xs = random.sample(range(1000), 100)
|
||||
assert quicksort(xs) == sorted(xs)
|
||||
assert qs(xs) == sorted(xs)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,33 @@
|
||||
# Write a groupby function that isn’t affected by sorting.
|
||||
import collections
|
||||
|
||||
|
||||
def groupby(func, seq):
|
||||
groups = collections.defaultdict(list)
|
||||
for item in seq:
|
||||
groups[func(item)].append(item)
|
||||
return groups
|
||||
|
||||
|
||||
def main():
|
||||
# Explicitly defined test data for clarity.
|
||||
xs = [0, 1, 2, 3, 4, 5, 6, 7]
|
||||
|
||||
assert groupby(lambda x: x % 2, xs) == {
|
||||
0: [0, 2, 4, 6],
|
||||
1: [1, 3, 5, 7],
|
||||
}
|
||||
|
||||
assert groupby(
|
||||
lambda x: 'even' if x % 2 == 0 else 'odd',
|
||||
xs,
|
||||
) == {'even': [0, 2, 4, 6], 'odd': [1, 3, 5, 7]}
|
||||
|
||||
assert groupby(lambda x: x > 5, xs) == {
|
||||
False: [0, 1, 2, 3, 4, 5],
|
||||
True: [6, 7],
|
||||
}
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,29 @@
|
||||
# Write a groupby function that returns lists of results instead of
|
||||
# generators.
|
||||
|
||||
import pprint
|
||||
|
||||
|
||||
def groupby(iterable, key=None):
|
||||
'''
|
||||
Return a dictionary of lists of items grouped by the key function.
|
||||
|
||||
Note that as opposed to the itertools.groupby function, this function
|
||||
does not require the iterable to be sorted.
|
||||
'''
|
||||
if key is None:
|
||||
key = lambda x: x
|
||||
groups = {}
|
||||
for item in iterable:
|
||||
groups.setdefault(key(item), []).append(item)
|
||||
return groups
|
||||
|
||||
|
||||
def main():
|
||||
# Demo data from the itertools docs
|
||||
pprint.pprint(groupby('AAAABBBCCDAABBB'))
|
||||
pprint.pprint(groupby('AAAABBBCCD'))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user