Think Python by Allen B. Downey

Think Python by Allen B. Downey

Author:Allen B. Downey [Allen B. Downey]
Language: eng
Format: epub, mobi, pdf
Tags: COMPUTERS / Programming Languages / Python
ISBN: 9781449330712
Publisher: O'Reilly Media
Published: 2012-08-08T16:00:00+00:00


Random Words

To choose a random word from the histogram, the simplest algorithm is to build a list with multiple copies of each word, according to the observed frequency, and then choose from the list:

def random_word(h): t = [] for word, freq in h.items(): t.extend([word] * freq) return random.choice(t)

The expression [word] * freq creates a list with freq copies of the string word. The extend method is similar to append except that the argument is a sequence.

Exercise 13-7.

This algorithm works, but it is not very efficient; each time you choose a random word, it rebuilds the list, which is as big as the original book. An obvious improvement is to build the list once and then make multiple selections, but the list is still big.

An alternative is:

Use keys to get a list of the words in the book.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.