Search code examples
pythonlistsum

how to solve this problem sum of the element of list in triangle format


I was attempting the sum of elements of the list. where I have to add the adjacent elements of the list and create a new list and repeat the process until I have the last element which will be the answer. I am able to solve the list of lengths less than 5 but I am not able to generalize the solution for any given list. Help me to solve this problem. below is my starting code: here is the example; general example of the problem

lst=[]
n=int(input())

for i in range(0,n):
 num = int(input())

  lst.append(num)
 print(lst)
 sum1=[]
for i in range(1,len(lst)):
  sum=i+i+1
  sum1.append(sum)

print(sum1)

Solution

  • A simple understandable function:

    def solve(seq):
        
        while len(seq) > 1:
            res = []
            for i in range(len(seq) - 1):
                res.append(seq[i] + seq[i+1])
            print(res)
            seq = res
            
        return res[0]
    
    solve([1,2,3,4])
    

    The idea is to find adjacent sums and store in a new list. Keep doing till length becomes 1.

    Some higher order function magic can be added to this if the logic becomes clear to someone.