user1580256
user1580256

Reputation: 25

How do i make a list change like this?

I need a python program that starts with the list a=[1] and then changes it to be 2 then 3 ... then 5 then adds another element and the list becomes 1,1 then becomes 1,2, etc until it becomes 5,5 and adds another element and becomes 1,1,1 and keeps going until it has 11 elements equal to 5 so it ends with 5,5,5,5,5,5,5,5,5,5,5

Upvotes: 0

Views: 139

Answers (4)

Inbar Rose
Inbar Rose

Reputation: 43437

this is a function that can receive this list at any state along its process and know how to handle it. sorry its a long answer, i wanted to provide as much help as i could. and i know the code is not the nicest is could be.

def growth(mylist):
    new = False
    i = 0
    mylist = [r for r in reversed(mylist)]
    while new is False:
        if mylist[i] < 5:
            mylist[i] += 1
            break
        elif i == len(mylist)-1:
            new = True
        else:
            i+=1
        if i >= len(mylist):
            break
    if new == True:
        mylist = [1 for r in xrange(len(mylist)+1)]
    mylist = [r for r in reversed(mylist)]
    return mylist

some testing:

#get at start:
a = [1]
print a
for i in xrange(10):
    a = growth(a)
    print a

result:

>>> 
[1]
[2]
[3]
[4]
[5]
[1, 1]
[1, 2]
[1, 3]
[1, 4]
[1, 5]
[2, 5]

and

print    
#get in middle:
a = [1,3]
print a
for i in xrange(10):
    a = growth(a)
    print a

result:

>>>
[1, 3]
[1, 4]
[1, 5]
[2, 5]
[3, 5]
[4, 5]
[5, 5]
[1, 1, 1]
[1, 1, 2]
[1, 1, 3]
[1, 1, 4]

and finally:

print
#get late:
a = [1,1,3,5]
print a
for i in xrange(10):
    a = growth(a)
    print a

result:

>>>
[1, 1, 3, 5]
[1, 1, 4, 5]
[1, 1, 5, 5]
[1, 2, 5, 5]
[1, 3, 5, 5]
[1, 4, 5, 5]
[1, 5, 5, 5]
[2, 5, 5, 5]
[3, 5, 5, 5]
[4, 5, 5, 5]
[5, 5, 5, 5]

Upvotes: 0

rsegal
rsegal

Reputation: 401

Since this seems like a homework question, you're only going to get an answer that puts you on the right track.

It seems to me, that you want the following behavior:

[1]
[2]
[3]
[4]
[5]
[1,1]
[1,2]
[1,3]
[1,4]
[1,5]
[2,5]

So it seems like you're adding elements forward, but then incrementing them backwards.

I'd look up modular arithmetic, to see how you could make a incrementing backwards clear your list back to 1's.

Once you do that, consider the range of (x mod 4) + 1.

Upvotes: 2

Sven Marnach
Sven Marnach

Reputation: 601351

You can use a for loop together with itertools.product():

from itertools import product

for n in range(1, 12):
    for a in product(range(1, 6), repeat=n):
        # Do whatever you want to do for each of the tuples

This does not create a single list that is changed in every iteration, but rather creates a new tuple for each iteration.

Upvotes: 2

Andrew Clark
Andrew Clark

Reputation: 208395

from itertools import chain, product

n = range(1, 6)
for a in chain.from_iterable(product(n, repeat=i) for i in range(1, 12)):
    # do whatever you want to with a

Upvotes: 3

Related Questions