From b089608e2eaace0b52ee1163fec361530a6a5049 Mon Sep 17 00:00:00 2001 From: dbecad Date: Sun, 12 Apr 2020 11:07:21 -0700 Subject: [PATCH] Adding recursive generators using the "yield from" statment --- README.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/README.md b/README.md index 6cde050..3a67a11 100644 --- a/README.md +++ b/README.md @@ -238,7 +238,24 @@ def count(start, step): >>> next(counter), next(counter), next(counter) (10, 12, 14) ``` +### Recursive generator +* **Generators can be recursive using the yield from statment.** +```python +def depth_first(trie, current_word = ''): + if trie is None: + yield current_word + else: + for letter, new_trie in trie.items(): + yield from depth_first(new_trie, current_word + letter) +``` + +```python +>>> trie={'b': {'a': {'b': {'y': None}, 'd': None,'n': {'k': None}}, 'o': {'x': None}}, +... 't': {'e': {'a': None,'d': None,'n': None}, 'o': None}} +>>> [w for w in depth_first(trie)] +['baby', 'bad', 'bank', 'box', 'tea', 'ted', 'ten', 'to'] +``` Type ----