Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Itertools.Permutations()

Why does itertools.permutations() return a list of characters or digits for each permutation, instead of just returning a string?

For example:

>>> print([x for x in itertools.permutations('1234')]) >>> [('1', '2', '3', '4'), ('1', '2', '4', '3'), ('1', '3', '2', '4') ... ] 

Why doesn't it return this?

>>> ['1234', '1243', '1324' ... ] 
like image 666
kennysong Avatar asked Nov 13 '11 18:11

kennysong


People also ask

How do you run a permutation in Python?

First import itertools package to implement the permutations method in python. This method takes a list as an input and returns an object list of tuples that contain all permutations in a list form.

What is Python permutation?

Permutations means different orders by which elements can be arranged. The elements might be of a string, or a list, or any other data type. It is the rearrangement of items in different ways. Python has different methods inside a package called itertools, which can help us achieve python permutations.

What does Python Itertools Groupby () do?

groupby() This method calculates the keys for each element present in iterable. It returns key and iterable of grouped items.


1 Answers

itertools.permutations() simply works this way. It takes an arbitrary iterable as an argument, and always returns an iterator yielding tuples. It doesn't (and shouldn't) special-case strings. To get a list of strings, you can always join the tuples yourself:

list(map("".join, itertools.permutations('1234'))) 
like image 155
Sven Marnach Avatar answered Sep 22 '22 02:09

Sven Marnach