Home > Net >  How can I find the sum of the numbers in a triangle given a list using Python?
How can I find the sum of the numbers in a triangle given a list using Python?

Time:03-07

Given a list such as the following: [1, 5, 8, 13, 4], I want to find the sum of two consecutive numbers in the following form (taking into account that if the numbers of a list is not even, the last numbers is added to the list by itself):

[1, 5, 8, 13, 4]
   [6, 21, 4]
    [27, 4]
     [31]

or

[1, 12, 7, 3, 15, 4]
   [13, 10, 19]
     [23, 19]
       [42]

We only need the last number so: results = [31] or result = [42].

CodePudding user response:

def fun(array):
  new_array = []
  for i in range(0, len(array), 2):
    if i % 2 == 0 and i < len(array) - 1:
      new_array.append(array[i]   array[i   1])
    else:
      new_array.append(array[i])
  return new_array;

array = [1, 5, 8, 13, 4]
while True:
  print(array)

  if len(array) == 1:
    break
  
  array = fun(array)

CodePudding user response:

Literally just add them together, it has the same result. You can even use the builtin function sum

  • Related