So i have to write a function that adds the sum of the two last numbers in a list together and adds this sum to the list. I have to do this 3 times, i could either do it without a loop or with a loop, i chose to do the difficult path, because i want to challenge myself, but i'm a bit stuck.
When i run the code with input print(append_sum([1, 1, 2])) it returns the correct value, but when i input print(append_sum([2, 5])) it only return 2, 5, 7
Full code is below:
#Write your function here
def append_sum(lst):
i = 0
for i in lst:
lst.append(lst[-1] lst[-2])
i = 1
if i == 3:
return lst
#Uncomment the line below when your function is done
print(append_sum([1, 1, 2]))
CodePudding user response:
You need not iterate every item in list.
def append_sum(lst):
repetitions = 3
for i in range(repetitions):
lst.append(lst[-1] lst[-2])
return lst
print(append_sum([1, 1, 2]))
Output:
[1, 1, 2, 3, 5, 8]
CodePudding user response:
You are overwriting i
variable in the for loop. Change the name to a different variable.
#Write your function here
def append_sum(lst):
counter = 0
for i in lst:
lst.append(lst[-1] lst[-2])
counter = 1
if counter == 3:
return lst
#Uncomment the line below when your function is done
print(append_sum([1, 1, 2]))
It is generally a really bad practice to use a, b, c, x, y, z, i, j, k
etc as variable names, as it makes the code less readable. Please use better variable names.
# Write your function here
def append_sum(numbers_list):
counter = 0
for number in numbers_list:
numbers_list.append(numbers_list[-1] numbers_list[-2])
counter = 1
if counter == 3:
return numbers_list
# Uncomment the line below when your function is done
print(append_sum([2, 5]))
In fact, for this case, you don't even need to iterate over the list.
# Write your function here
def append_sum(numbers_list):
if len(numbers_list) < 2:
raise Exception("List must have at least two numbers")
for counter in range(1, 3 1):
numbers_list.append(numbers_list[-1] numbers_list[-2])
if counter == 3:
return numbers_list
# Uncomment the line below when your function is done
print(append_sum([1, 1, 2]))