[Tutor] computation problem
Mark Lawrence
breamoreboy at gmail.com
Sun Nov 28 14:34:23 EST 2021
On 28/11/2021 19:14, marcus.luetolf at bluewin.ch wrote:
> Hello Experts
>
>
>
> I'd like to write a python code to find all possible combinations of a list
> of n items.
>
> If, for example, a list L consists of 4 items, n = 4, L = ['abcd'], the
> code should print out 24 different combinations from ['abcd'] to ...['dcba']
>
> I tried several solutions posted on stackoverflow using itertools but none
> gave the sought for combinations.
>
> I'm aware the complexity of a a code using for loops might be exponential .
>
> Could anybody tell me a text or tutorial how to approach tist task by python
> ?
>
You have a list which contains one item, a string 'abcd'. If you only
want the string used the following works.
python3.9
Python 3.9.7 (default, Sep 10 2021, 14:59:43)
[GCC 11.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from itertools import permutations
>>> l='abcd'
>>> for a in permutations(l):print(a)
...
('a', 'b', 'c', 'd')
('a', 'b', 'd', 'c')
('a', 'c', 'b', 'd')
('a', 'c', 'd', 'b')
('a', 'd', 'b', 'c')
('a', 'd', 'c', 'b')
('b', 'a', 'c', 'd')
('b', 'a', 'd', 'c')
('b', 'c', 'a', 'd')
('b', 'c', 'd', 'a')
('b', 'd', 'a', 'c')
('b', 'd', 'c', 'a')
('c', 'a', 'b', 'd')
('c', 'a', 'd', 'b')
('c', 'b', 'a', 'd')
('c', 'b', 'd', 'a')
('c', 'd', 'a', 'b')
('c', 'd', 'b', 'a')
('d', 'a', 'b', 'c')
('d', 'a', 'c', 'b')
('d', 'b', 'a', 'c')
('d', 'b', 'c', 'a')
('d', 'c', 'a', 'b')
('d', 'c', 'b', 'a')
>>>
--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.
Mark Lawrence
More information about the Tutor
mailing list