Last active
December 17, 2015 03:13
-
-
Save ijkilchenko/c2fc01026e1cbdcd9e83 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# author: @ijkilchenko | |
# MIT License | |
def words_over_vocab(vocab, n): | |
return _words_over_vocab(vocab, '', n) | |
def _words_over_vocab(vocab, word, n): | |
if len(word) == n: | |
yield word | |
else: | |
for letter in vocab: | |
yield from _words_over_vocab(vocab, word + letter, n) | |
if __name__ == '__main__': | |
assert len(list(words_over_vocab('abcde', 2))) == 25 | |
assert len(list(words_over_vocab('abcde', 7))) == 5**7 | |
g = words_over_vocab('abc', 4) | |
for word in g: | |
print(word) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Python generator defined recursively
words_over_vocab
takes a string which defines the vocabulary and an integern
which defines the length of words to be yielded.