Skip to content

Instantly share code, notes, and snippets.

@ijkilchenko
Last active December 17, 2015 03:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ijkilchenko/c2fc01026e1cbdcd9e83 to your computer and use it in GitHub Desktop.
Save ijkilchenko/c2fc01026e1cbdcd9e83 to your computer and use it in GitHub Desktop.
# 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)
@ijkilchenko
Copy link
Author

Python generator defined recursively

words_over_vocab takes a string which defines the vocabulary and an integer n which defines the length of words to be yielded.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment