Assuming that [1, 6, 3, 15, 54]
gets reduced to [-11]
in the end, you can just use recursion for this. What recursion will do here is keep calling the same function over and over again, until a base case is met. In your case, it will keep reducing the list on each recursive call, until the length of the list only has one element. I'm also assuming that you want to return the final singleton list at the end.
Recursion Approach:
lst = [1, 6, 3, 15, 54]
def reduce_list(l):
if len(l) == 1:
return l
return reduce_list([y - x for x, y in zip(l, l[1:])])
print(reduce_list(lst))
Which Outputs:
[-11]
Note: zip()
was used to pair every 2 elements elements together in the list, and minus the second element from the first element.
Here is an example that breaks down the above usage of zip()
:
>>> lst = [1, 6, 3, 15, 54]
>>> zipped = list(zip(lst, lst[1:]))
[(1, 6), (6, 3), (3, 15), (15, 54)]
>>> print([y - x for x, y in zipped])
[5, -3, 12, 39]
Additionally, anything done with recursion can be done with a simple loop, which @poke has nicely shown.
EDIT:
Since the above code is prone to RecursionError: maximum recursion depth
errors with lists of size 1000 or greater, because 1000 is the recusion limit, you can see this post for more details on how to increase the limit. Alternatively, you can also just make an iterative version that is bypasses this problem, as shown below.
Iterative Approach:
lst = [1, 6, 3, 15, 54]
def reduce_list(l):
return [y - x for x, y in zip(l, l[1:])]
# Since 5 elements reduce to 1, 4 iterations only needed
for _ in range(len(lst) - 1):
lst = reduce_list(lst)
print(lst)
# [-11]