3 ms·
Python recursive solution for generating permutations: s = 'abcd' prefix = '' permutation(prefix, s) def permutation(prefix, s): n = len(s)
by rajathagasthya 9y ago
Python recursive solution for generating permutations:
s = 'abcd'
prefix = ''
permutation(prefix, s)
def permutation(prefix, s):
n = len(s)
if n == 0:
print(prefix)
else:
for i in range(n):
permutation(prefix + s[i], s[:i] + s[i+1:])
- shakna 9y agoWouldn't you hit Python's recursive limit rather quickly doing this? There might be a way to avoid messing with the recursive depth if you swapped out the main part of the for loop for a generator though.
- Veedrac 9y agoYou'd need to be finding the permutations for a list ~1000 elements long, but for such a list there are far too many permutations for such a request to be meaningful.
- raymondh 9y agoAn iterative Python recipe can be found in the docs: https://docs.python.org/3/library/itertools.html#itertools.permutations https://docs.python.org/3/library/itertools.html#itertools.p...
- rajathagasthya 9y agoStraight from the horse's mouth! Thanks, Raymond :)