[Tutor] computation problem

Mats Wichmann mats at wichmann.us
Sun Nov 28 14:30:42 EST 2021


On 11/28/21 12: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
> ?
> 

maybe if you showed what you've tried, and showed why itertools doesn't 
work for you...

['abcd'] isn't a list of four items, it's a list of one item.  If you 
want to treat the characters in the string as separate items, you have 
to break it apart and, if you want it displayed like you indicate above, 
combine it back together again. Do you know how to do that?

itertools.permutations will definitely do the "heavy lifting" for you.

 >>> from itertools import permutations
 >>> len(list(permutations(['a', 'b', 'c', 'd'])))
24

the list() is because permutations returns an iterator, not a list. 
Normally you'd end up iterating over the result, which is why it doesn't 
take the time to force it to a list itself.



More information about the Tutor mailing list