I am working on a list exercise in Python where I am creating a function that appends the sum of the last two numbers in a list. Then I need to repeat the process two more times using the new list created by the first returned result.
I have the first part right and I can get the code to add the first value to the list. The problem is I can't figure out how to repeat the process two more times.
Here is what I have;
#This section adds the last two numbers together and appends to lst
lst.append(lst[-1] + lst[-2])
return lst
#I tried doing this but it produced the exact same result
lst.append(lst[-1] + lst[-2])
return lst
lst.append(lst[-1] + lst[-2])
return lst
#Uncomment the line below when your function is done
print(append_sum([1, 1, 2]))
#After I run the code I get
[1, 1, 2, 3]
This is because you return the list after your first call, thus the second two calls don't happen.
Just replace your calls with a for loop as follows and you should be fine:
def list_sum(lst):
for _ in range(3):
lst.append(lst[-1] + lst[-2])
return lst
print(list_sum([1,1,2]))
(this prints [1,1,2,3,5,8]
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.