Search code examples
pythonloopsrandom-walk

Random walk Python exercise loop


I am doing python exercise and I can not finish it. I need to a create array and fill it 25 numbers, every number will be the sum of previous one and the value drawn from the set (-5, 5).

import numpy as np import random

def prog_list(mylist):
    mylist = [0]
    addlist = [-5,5]
    sum_list = 0
    for i in mylist:
        if len(mylist) < 25:
            sum_list = random.choice(addlist) + mylist[i-1]
            mylist.append(sum_list)
        else:
            return mylist
        
for x in prog_list(mylist):
    print(x)

When I print x I've got

IndexError: list index out of range

Solution

  • for i in mylist:
        if len(mylist) < 100:
            sum_list = random.choice(addlist) + mylist[i-1]
            mylist.append(sum_list)
        else:
            return mylist
    

    This construct will get value of element of mylist as i. First element is 0 so you get one of {-5,5} + mylist[-1] ([-1] means last element in python language), this result in either -5 or 5, then you get that value less 1 which is either -6 or 4, but there is not enough elements to get -6 (i.e. 6 from right) or 4 (i.e. 5 from left) element, thus IndexError. To avoid that you might replace your for using following while

    while len(mylist) < 100:
        sum_list = random.choice(addlist) + mylist[-1]
        mylist.append(sum_list)
    return mylist