from itertools import permutations
word, num = input().split(" ")
permutations = list(permutations(word, int(num)))
permutations.sort()
[print("".join(i)) for i in permutations]
i don't understand the last line why the [ ] brackets.
Umesh Kumar The [ ] brackets are for list comprehension docs.python.org/3/tutorial/datastructures.html
That thing inside the brackets is a generator. Here it is, expanded. We need to add a helper variable result, although as it turns out, itʼs useless in this case.
result = []
for i in permutations:
value = print("".join(i))
result.append(value)
It’s a bit strange, as print() returns nothing in Python 3 and yields a syntax error in Python 2. But it indeed prints the values in permutations.
srig
Python enthusiast
By using
permutationsas the name of a variable, the code is masking the classpermutationsin moduleitertools. Tryhelp(permutations)in your Python Shell. You will get Help onlistobject, not Help on classpermutationsin moduleitertools.I would pass a prompt to
input()and rename the variable which is set to the permutations:word, num = input("Enter a word and an integer with a space in between: ").split(" ") perms = list(permutations(word, int(num))) perms.sorted()As you can see, you have tuples of permutations in the list
permswhich is sorted in-place.Now let's see what's happening with the code below:
[print("".join(i)) for i in perms]That is a list comprehension, a concise way to create lists.
"".join(i)concatenates the strings in each tuple of the list.print("".join(i))prints the above concatenation to sys.stdout.Of note, the print() function returns
None. Onceprint()is done printing, on each call it returnsNone, so all that the list has areNones.I would rewrite the code, like so:
from itertools import permutations user_input = input("Enter a word and an integer with a space in between: ") word, num = user_input.split(" ") perms = list(permutations(word, int(num))) perms.sort() for perm in perms: print("".join(perm))If you want to be able to reuse the list, you could assign it to a variable:
perms_catted = ["".join(perm) for perm in perms]Hope that helps.