Random walk Python exercise loop

193 Views Asked by At

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
3

There are 3 best solutions below

0
On BEST ANSWER
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
0
On
for i in mylist

iterates over the items in your list, so on the first step when you add or subtract 5, you will be trying to access the (5 - 1)th or the (-5 - 1)th element with mylist[i - 1], and that will give you an IndexError.

To get the current last element of your mylist, you should use

mylist[-1] instead of mylist[i - 1]
0
On

this works:

def prog_list(n):
    mylist = [0]
    #addlist = [-5,5]
    addlist = list(range(-5, 5+1))
    for i in range(1, n):
        _sum = random.choice(addlist) + mylist[i-1]
        mylist.append(_sum)
    return mylist

prog_list(25)

if you want to draw any integer from (-5, 5) you need this: addlist = list(range(-5, 5+1))

there is an even cleaner way to do it where you dont acces the list in every iteration:

def prog_list(n):
    mylist = []
    _sum = 0
    #addlist = [-5,5]
    addlist = list(range(-5, 5+1))
    for i in range(n):
        mylist.append(_sum)
        _sum += random.choice(addlist)
    return mylist
        
prog_list(25)