Use timeit.Timer
or ipython's %timeit
to check if
removing items from the middle of a list is slower than removing items
from the beginning.
Good way to invoke timeit
:
for N in 100 200 400 800 1600 3200 6400 128000 256000 512000 1024000; do python -m timeit -s "L0=range($N);L=L0[:]" -r 1 -n $N "L.pop(0)"; done
Answer: no, it's not.
python -m timeit -s "L0=range(1000000);L=L0[:]" -r 30 -n 10000 "L.pop(500000)"
File huge_text.txt is big: 10GB of loony sentenes. Write an iterator which returns words from this file, without reading the whole thing into memory. Print out the list of the ten most popular words.
Solution: words.py
Write a generator function which returns a few values. Launch it.
Retrieve a value using next
(the global function). Retrieve a
value using next
(a method of the generator object).
Write a program to find all anagrams in a list of words. E.g., for the list
['dog', 'elapses', 'house', 'pleases', 'God']
the program might say
elapses <~> pleases dog <~> God
Ignore the case of letters.
For development write the list directly in the program.
For testing use the following generator expression:
(line.strip() for line in open('/usr/share/dict/words'))
Hint: a word is a sequence of characters. Two words are anagrams, if their sequences of letters are the same, after sorting.
Example answer: anagrams.py
Write a function which returns a function which uses two variables from a closure. Retrieve the two variables from outside the function.
Look at the following example:
import random def f(): L = [] def g(): x = random.random() L.append(x) return L return g g = f() g() g()
What happens here?
Look at the following example:
import random def f(): L = [] def g(): x = random.random() L.append(x) return L def h(): x = random.random() L.append(x) return L return g, h g, h = f() g() h()
What happens here?