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

Time:10-17

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)

CodePudding user response:

The following seems reasonably simple:

n = int(input())
lst = [int(input()) for _ in range(n)]

while len(lst) > 1:
    lst[:] = map(sum, zip(lst, lst[1:]))  # all sums of neighbours
    print(lst)


# Output for 1 2 3 4
# [3, 5, 7]
# [8, 12]
# [20]

Some docs:

CodePudding user response:

Given 2 lists of equal length you could do this:

M = [1,2,3]
N = [5,6,7]
print(*map(sum, zip(M,N)))

CodePudding user response:

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.

  • Related