Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

A question about making a sort-of-counter.

2 views
Skip to first unread message

Justin Park

unread,
Mar 30, 2010, 5:31:58 PM3/30/10
to pytho...@python.org
Suppose I have a list.
a = list()
And suppose allowed digits as the element are 1,2,3,4,5.

What can I do in order to iterate over all possible values for each element?
For instance, the sequence of the list I want to have would be
[1,1,1,1,1]
[1,1,1,1,2]
[1,1,1,1,3]

....

[5,5,5,5,4]
[5,5,5,5,5]

How can I make it happen?

Thanks,
Justin.

Robert Kern

unread,
Mar 30, 2010, 5:58:34 PM3/30/10
to pytho...@python.org

def counter(n=5, length=5):
for i in xrange(n ** length):
x = []
for j in range(length):
i, r = divmod(i, n)
x.append(r)
yield [k+1 for k in x[::-1]]

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco

anon

unread,
Mar 30, 2010, 6:00:13 PM3/30/10
to


http://docs.python.org/library/itertools.html#itertools.product

from itertools import product

for item in product([1, 2], repeat=2):
print item

Justin Park

unread,
Mar 30, 2010, 6:12:28 PM3/30/10
to Chris Rebert, pytho...@python.org
Thanks!
It works!

Justin.

Chris Rebert wrote:


> On Tue, Mar 30, 2010 at 2:31 PM, Justin Park <h...@rice.edu> wrote:
>
>> Suppose I have a list.
>> a = list()
>> And suppose allowed digits as the element are 1,2,3,4,5.
>>
>> What can I do in order to iterate over all possible values for each element?
>> For instance, the sequence of the list I want to have would be
>> [1,1,1,1,1]
>> [1,1,1,1,2]
>> [1,1,1,1,3]
>>
>> ....
>>
>> [5,5,5,5,4]
>> [5,5,5,5,5]
>>
>> How can I make it happen?
>>
>

> allowed = range(1,6)
> length = 5
> for counter_tuple in product(allowed, repeat=length):
> counter_list = list(counter_tuple) # if you really need a list
> #do whatever with the counter value
>
> See the docs for itertools.product(); an example virtually identical
> to your situation is given:
> http://docs.python.org/library/itertools.html#itertools.product
>
> Cheers,
> Chris
> --
> http://blog.rebertia.com
>
>

Chris Rebert

unread,
Mar 30, 2010, 6:08:17 PM3/30/10
to Justin Park, pytho...@python.org
0 new messages