I have a list whose length can be anything depending on another variable. The values in the list start off the same so if length was 5 and the values were 1000 it would look like [1000,1000,1000,1000,1000]
def change_list(list1):
for x in list1[1:]:
list1[0] += x/2
for x in range(1,len(list1)):
list1[x] = list1[x]/2
for x in list1[2:]:
list1[1] += x/2
for x in range(2,len(list1)):
list1[x] = list1[x]/2
for x in list1[3:]:
list1[2] += x/2
for x in range(3,len(list1)):
list1[x] = list1[x]/2
for x in list1[4:]:
list1[3] += x/2
for x in range(4,len(list1)):
list1[x] = list1[x]/2
for x in list1[5:]:
list1[4] += x/2
return list1
list2= change_list(list1)
print (list2)
It works by halving the values after the index its on and adding them to the value of the index, the halved values stay halved and its repeated so after the first two for loops it looks like 3000, 500, 500, 500, 500 then 3000, 1250, 250 ,250, 250 then 3000, 1250, 500, 125, 125 finally 3000, 1250, 500 ,187.5 ,62.5 which works as all the values together make the same amount as the 5 1000s
I don't know how to change this to make it work for any length instead of 5 so if the list was 1000, 1000, 1000, 1000, 1000, 1000 the result would need to be 3500, 1500, 625,250, 93.75, 31.25 Please help i'm utterly stuck!
Try this:
def change_list(list1, index=0):
i = index + 1
while i < len(list1):
list1[i] /= 2
list1[index] += list1[i]
i += 1
if index < len(list1):
index += 1
list1 = change_list(list1, index=index)
return list1
list2 = change_list([1000, 1000, 1000, 1000, 1000])
I'm using recursion so that the function is called from within itself as many times as it takes to reach the end of the list, so you don't need to give it the length of the list.
Does it work for you?