This challenge was comparatively far easier than some of the other challenges in this section. I simply got the sum of the last two elements and appended the list. Rinsed and repeated until finished. This seemed to be a little inefficient. I’m sure this will be covered in later lessons but my curiosity is getting the best of me. How would I build a loop that terminates after a finite number of runs?
I don’t understand why this code doesn’t work. It’s …messy, yes, but I’m not following why it is only adding the last two elements one time and then repeating the answer instead of appending to the list and then adding the new last two elements together, so on and so forth.
I tried to use a for loop instead of while which seems to work too.
I need to stop creating all these variables along the way. I see it’s terribly inefficient but helps me get my mind around what is happening as I’ve not learnt how to properly debug yet. So i keep printing everything along the way to check.
def append_sum(lst):
for i in range(0,3):
last_item = lst[-1]
second_last_item = lst[-2]
combined = last_item + second_last_item
lst.append(combined)
#print(lst)
return lst
From seeing the other posts I guess i can pull all those variables and just do ,
def append_sum(lst):
for i in range(0,3):
lst.append(lst[-1] + lst[-2])
return lst
Hey, FWIW, I keep all of my code/notes open on my colab.research.google jupyter notebooks… I can’t remember everything
and
I can’t count the number of times having my jupyter notebooks available have helped me solve these exercises.
I put the for and range commands to work in order to iterate the append 3 times …
#Write your function here
def append_sum(lst):
for x in range(3):
lst.append((lst[-1] + lst[-2]))
return lst
#Uncomment the line below when your function is done
print(append_sum([1, 1, 2]))
Hi first post here! Sorry if I format something wrong but I don’t quite understand what I’m doing wrong here? This is the append sum challenge where it looks to add the last two values of a list then append the sum back into the list. I’m curious as to why my code prints:
[1, 1, 2, 3]
INSTEAD OF [1, 1, 2, 3, 5, 8]
I checked the solution, but as to my example I’m curious how to implement this if lets say the goal was to add and append until the list length were 50… or 500 ! Thanks again
def append_sum(lst):
i = 0
while i < len(lst):
sum1_3 = lst[-1] + lst[-2]
lst.append(sum1_3)
i += 1
return lst
Here I’m attempting to use a while loop that while the length of list is less than X sum last two indexs, then append to lst.
Hope this is enough information for someone to help ! Thanks