# Python: using a recursive algorithm as a generator

| | | | | | | | | | | |

👻 Check our latest review to choose the best laptop for Machine Learning engineers and Deep learning tasks!

Recently I wrote a function to generate certain sequences with nontrivial constraints. The problem came with a natural recursive solution. Now it happens that, even for relatively small input, the sequences are several thousands, thus I would prefer to use my algorithm as a generator instead of using it to fill a list with all the sequences.

Here is an example. Suppose we want to compute all the permutations of a string with a recursive function. The following naive algorithm takes an extra argument "storage" and appends a permutation to it whenever it finds one:

``````def getPermutations(string, storage, prefix=""):
if len(string) == 1:
storage.append(prefix + string)   # <-----
else:
for i in range(len(string)):
getPermutations(string[:i]+string[i+1:], storage, prefix+string[i])

storage = []
getPermutations("abcd", storage)
for permutation in storage: print permutation
``````

Now I want to turn my function into a generator, i.e. to yield a permutation instead of appending it to the storage list:

``````def getPermutations(string, prefix=""):
if len(string) == 1:
yield prefix + string             # <-----
else:
for i in range(len(string)):
getPermutations(string[:i]+string[i+1:], prefix+string[i])

for permutation in getPermutations("abcd"):
print permutation
``````

This code does not work (the function behaves like an empty generator).

Am I missing something? Is there a way to turn the above recursive algorithm into a generator without replacing it with an iterative one?

👻 Read also: what is the best laptop for engineering students?

We hope this article has helped you to resolve the problem. Apart from Python: using a recursive algorithm as a generator, check other abc Python module-related topics.

Want to excel in Python? See our review of the best Python online courses 2023. If you are interested in Data Science, check also how to learn programming in R.

By the way, this material is also available in other languages:

Julia Sikorski

Tallinn | 2023-03-25

Thanks for explaining! I was stuck with Python: using a recursive algorithm as a generator for some hours, finally got it done 🤗. Checked yesterday, it works!

Davies Williams

Prague | 2023-03-25

Thanks for explaining! I was stuck with Python: using a recursive algorithm as a generator for some hours, finally got it done 🤗. Will use it in my bachelor thesis

Manuel Ungerschaft

Berlin | 2023-03-25

I was preparing for my coding interview, thanks for clarifying this - Python: using a recursive algorithm as a generator in Python is not the simplest one. Will get back tomorrow with feedback

## Shop

Learn programming in R: courses

\$FREE

Best Python online courses for 2022

\$FREE

Best laptop for Fortnite

\$399+

Best laptop for Excel

\$

Best laptop for Solidworks

\$399+

Best laptop for Roblox

\$399+

Best computer for crypto mining

\$499+

Best laptop for Sims 4

\$

Latest questions

PythonStackOverflow

Common xlabel/ylabel for matplotlib subplots

PythonStackOverflow

Check if one list is a subset of another in Python

PythonStackOverflow

How to specify multiple return types using type-hints

PythonStackOverflow

Printing words vertically in Python

PythonStackOverflow

Python Extract words from a given string

PythonStackOverflow

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

PythonStackOverflow

Python os.path.join () method

PythonStackOverflow

Flake8: Ignore specific warning for entire file

## Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

How to specify multiple return types using type-hints

Printing words vertically in Python

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries