A question about making a sort-of-counter.

Robert Kern robert.kern at gmail.com
Tue Mar 30 23:58:34 CEST 2010


On 2010-03-30 16:31 PM, Justin Park 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?

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




More information about the Python-list mailing list