[Tutor] for loop results into list

Evert Rol evert.rol at gmail.com
Sun Sep 5 20:26:45 CEST 2010


> Hello all,
> 
> I'm having a little problem figuring out how to accomplish this simple task. I'd like to take a list of 6 numbers and add every permutation of those numbers in groups of four. For example for 1, 2, 3, 4, 5, 6 add 1 + 1 + 1 +1 then 1 + 1 + 1 +2 etc. until reaching 6 + 6 + 6 + 6. Using a for loop, that was the easy part, now I'd like to take the results and count the number of times each number occurs.
> My problem occurs when I try to create a list from the results of the for loop, it puts each individual number into its own list. I've looked everywhere for the solution to this and can find nothing to help.
> 
> Any suggestions would be much appreciated

If you had some code, that would be very helpful. Now it's a bit of guesswork what exactly you have (code tends to be clearer than a full paragraph or two of text).
At least, I currently don't understand what your problem is (or what your for-loop involves).
Eg, are you looping and calling a function recursively, do you have four nested loops (or nested list comprehensions)? Or some other convenient loop to step through all combinations?

Anway, if you have a recent Python version (2.7 or 3.1), the itertools module provides a handy utiity: http://docs.python.org/py3k/library/itertools.html#itertools.combinations_with_replacement
Eg,

>>> map(sum, combinations_with_replacement(range(1,7), 4))
[4, 5, 6, 7, 8, 9, 6, 7, 8, 9, 10, 8, 9, 10, 11, 10, 11, 12, 12, 13, 14, 7, 8, 9, 10, 11, 9, 10, 11, 12, 11, 12, 13, 13, 14, 15, 10, 11, 12, 13, 12, 13, 14, 14, 15, 16, 13, 14, 15, 15, 16, 17, 16, 17, 18, 19, 8, 9, 10, 11, 12, 10, 11, 12, 13, 12, 13, 14, 14, 15, 16, 11, 12, 13, 14, 13, 14, 15, 15, 16, 17, 14, 15, 16, 16, 17, 18, 17, 18, 19, 20, 12, 13, 14, 15, 14, 15, 16, 16, 17, 18, 15, 16, 17, 17, 18, 19, 18, 19, 20, 21, 16, 17, 18, 18, 19, 20, 19, 20, 21, 22, 20, 21, 22, 23, 24]

seems to do what you want.

But, I'd still say to adopt your own code first, and when you've learned from that, just use the one-liner above. You're most welcome to ask your question, best done in combination with code, actual output and expected output. Then we can point you in the right direction.

Cheers,

  Evert



More information about the Tutor mailing list