sum of the previous two elements of the list
I want to use for loop to test whether each member of list has the sum of the previous two elements of the list. The output should something like this. Thanks in advance
list = [1,1,2,3,5,8,13,21,34,55,85,143]
input :[1,1,2,3,5,8,13,21,34,55,85,143]
output:
0+1=1 True 1+1=2 True 1+2=3 True 2+3=5 True 3+8=11 True 8+13=21 True 13+21=34 True 21+34=55 True 34+55=89 False 55+85 =140 False
I tired some loop logic but not able to get the desired result e.g
l =[1,1,2,3,5,8,13,21,34,55,85,143] sum=0 for element in l: print(element) sum +=element print(sum)
my_list = [1,1,2,3,5,8,13,21,34,55,88,143] prev_prev_item = 0 for idx in range(1, len(my_list)): print(idx, my_list[idx], my_list[idx] == my_list[idx-1] + prev_prev_item) prev_prev_item = my_list[idx-1]
output –
1 1 True 2 2 True 3 3 True 4 5 True 5 8 True 6 13 True 7 21 True 8 34 True 9 55 True 10 88 False 11 143 True
You can zip the list together with itself and iterate over that. For the first list in the zip prepend with [0]
. Avoiding the indices should help the readability:
l = [1,1,2,3,5,8,13,21,34,55,88,143] for a, b, c in zip([0]+l, l, l[1:]): print(f"{a} + {b} = {c} {a + b == c}")
Prints:
0 + 1 = 1 True 1 + 1 = 2 True 1 + 2 = 3 True 2 + 3 = 5 True 3 + 5 = 8 True 5 + 8 = 13 True 8 + 13 = 21 True 13 + 21 = 34 True 21 + 34 = 55 True 34 + 55 = 88 False 55 + 88 = 143 True
list = [1,1,2,3,5,8,13,21,34,55,88,143] for i in range(len(list)-2): if (list[i+2] == (list[i]+list[i+1])): print(list[i],'+',list[i+1],'=',list[i+2],'True') else: print(list[i],'+',list[i+1],'=',list[i+2],'False')
Simply go through the list (for loop) and compare the sum of the ith and i+1th item with the i+2th item (if statement). It should be easy to follow. The output should be the same as yours:
1 + 1 = 2 True 1 + 2 = 3 True 2 + 3 = 5 True 3 + 5 = 8 True 5 + 8 = 13 True 8 + 13 = 21 True 13 + 21 = 34 True 21 + 34 = 55 True 34 + 55 = 88 False 55 + 88 = 143 True