1

I am trying to make a script that if I gave it a list of words such as ('1', '2', '3') it would give me:

1 12 13 123 232 2 21 23 213 231 3 31 32 31 32 312 321

I have tried itertools but I couldn't figure it out How can I do this?

Thankyou

  • https://stackoverflow.com/questions/464864/how-to-get-all-possible-combinations-of-a-list-s-elements – konstantin durant May 26 '22 at 06:32
  • https://stackoverflow.com/questions/50242147/all-possible-permutations-of-multiple-lists-and-sizes – Yanirmr May 26 '22 at 06:34
  • https://docs.python.org/3/library/itertools.html#itertools.permutations sounds useful for your need – Yanirmr May 26 '22 at 06:34
  • Does this answer your question? [How to get all possible combinations of a list’s elements?](https://stackoverflow.com/questions/464864/how-to-get-all-possible-combinations-of-a-list-s-elements) – Nick May 26 '22 at 06:36
  • 1
    Is 232 a mistake? – mozway May 26 '22 at 06:39

1 Answers1

0

You need a variant of the powerset recipe from itertools using permutations instead of combinations:

from itertools import permutations, chain

def powerperm(iterable):
    s = list(iterable)
    return chain.from_iterable(permutations(s, r) for r in range(1, len(s)+1))

inp = ('1', '2', '3')

out = list(map(''.join, powerperm(inp)))
out

output: ['1', '2', '3', '12', '13', '21', '23', '31', '32', '123', '132', '213', '231', '312', '321']

mozway
  • 194,879
  • 13
  • 39
  • 75