Hello,
I make an exercise from a book : Think Python: How to Think Like a Computer Scientist by Allen B. Downey, Version 1.1.22, random words exercise 7.
I made a script like this (see below) but how can I make list (named book) just once and since then after each execution of the script it will make random choice from this list (if I well understand the task). There are more alternatives (in this manual book) and I don't know which one is more efficient, can you also tell me?
import random
def random_word(h):
k=histogram(h)
## print k
t=[]
for word, freq in k.items():
t.extend([word]*freq) # output is a list but it will be build again after each execution of the script
return random.choice(t)
def histogram(h):
d = dict()
for c in h:
if c not in d:
d[c] = 1
else:
d[c] += 1
return d
print random_word('I went out for a walk')
Thank you
Vlady