Write a function named append_sum that has one parameter — a list named named lst. The function should add the last two elements of lst together and append the result to lst. It should do this process three times and then return lst. For example, if lst started as [1, 1, 2], the final result should be [1, 1, 2, 3, 5, 8].
solutions-1
def append_sum(lst):
lst.append(lst[2] lst[1])
lst.append(lst[2] lst[1])
lst.append(lst[2] lst[1])
return lst
print(append_sum([1, 1, 2]))
ans = [1, 1, 2, 3, 3, 3]
solution-2
def append_sum(lst):
lst.append(lst[-1] lst[-2])
lst.append(lst[-1] lst[-2])
lst.append(lst[-1] lst[-2])
return lst
print(append_sum([1, 1, 2]))
ans = [1, 1, 2, 3, 5, 8]
CodePudding user response:
Consider: lst[2]
is an absolute index, while lst[-1]
is a relative index, based on the length of the list. If the list grows beyond 3 elements (where lst[2]
would work) then lst[2]
is still going to give the same answer, no matter how big the list gets. However, the same cannot be true if you count indices from the end of a list that can expand.
This is easily shown with:
a = [1, 2, 3]
for x in range(4, 10):
a.append(x)
print("Forward index value", a[2])
print("Reverse index value", a[-1])
CodePudding user response:
If you are baffled by some python
behiavor it is often useful to add print
and look what happen, in your code please run following code and try to decude why behavior is different that what you desired
def append_sum(lst):
print(lst,lst[2],lst[1])
lst.append(lst[2] lst[1])
print(lst,lst[2],lst[1])
lst.append(lst[2] lst[1])
print(lst,lst[2],lst[1])
lst.append(lst[2] lst[1])
print(lst)
return lst
CodePudding user response:
You can trace like below:
>>> lst = [1, 1, 2]
>>> lst.append(lst[2] lst[1])
>>> lst
[1, 1, 2, 3]
>>> lst.append(lst[2] lst[1])
>>> lst
[1, 1, 2, 3, 3]
>>> lst.append(lst[2] lst[1])
>>> lst
[1, 1, 2, 3, 3, 3]
but in second function
you chenage you last element
and use in sum
:
>>> lst = [1, 1, 2]
>>> lst.append(lst[-1] lst[-2])
>>> lst
[1, 1, 2, 3]
>>> lst.append(lst[-1] lst[-2])
>>> lst
[1, 1, 2, 3, 5]
>>> lst.append(lst[-1] lst[-2])
>>> lst
[1, 1, 2, 3, 5, 8]