Home > OS >  Is there a way for python to print out itertools.permutations on a word without the list?
Is there a way for python to print out itertools.permutations on a word without the list?

Time:09-28

So, whenever I run itertools.permutations on a string, it comes out like this:

input code:

import itertools
import pprint

pprint.pprint(list(itertools.permutations("par")))

My output is this array:

[('p', 'a', 'r'),
 ('p', 'r', 'a'),  
 ('a', 'p', 'r'),  
 ('a', 'r', 'p'),  
 ('r', 'p', 'a'),  
 ('r', 'a', 'p')]  

This is a big problem with larger strings. I need a way to print these out as a normal looking line such as:

par
pra
apr
arp
rpa
rap

or in a list, like

par, pra, apr, arp, rpa, rap

I'm new to programming, so if something seems painfully obvious, my bad!

CodePudding user response:

Use map:

>>> list(map(''.join, itertools.permutations("par")))
['par', 'pra', 'apr', 'arp', 'rpa', 'rap']

Or a list comprehension:

>>> [''.join(l) for l in itertools.permutations("par")]
['par', 'pra', 'apr', 'arp', 'rpa', 'rap']
>>> 

Or as @ShadowRanger mentioned, you could do it even better:

for x in map(''.join, itertools.permutations("par")):
    print(x)

Output:

par
pra
apr
arp
rpa
rap

Or also:

for x, y, z in itertools.permutations("par"):
    print(x   y   z)

CodePudding user response:

>>> for perm in itertools.permutations("par"):
...     print("".join(perm))
... 
par
pra
apr
arp
rpa
rap

CodePudding user response:

Use for loop (If you want to print directly)-

import itertools
import pprint

a = list(itertools.permutations("par"))

for i,j,k in a:
    print(f'{i}{j}{k}') # Output

Or List Comprehension (If you want a list) -

output = [f'{i}{j}{k}' for i,j,k in a]
print(output)
  • Related