Friday, May 13, 2022

[FIXED] why is this two functions not giving me the same answer?

Issue

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]


Solution

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])


Answered By - roganjosh
Answer Checked By - Senaida (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.