Search code examples
pythonsumdigitstriangle

Sum of the numbers in a triangular shape using Python (only using one digit)?


Given a list such as the following: [1, 5, 8, 13, 4], we want to find the sum of two consecutive numbers as shown below. We should take into account that if a number on the list has more than one digit, it needs to be changed the digit in the last position (most to the right). Also, we should consider that if the total numbers of the list are odd, the last numbers is added to the list by itself:

[1, 5, 8, 13, 4]
    [6, 1, 4] --> #21 becomes 1
     [7, 4]
      [11]

or

[1, 12, 7, 3, 15, 4]
      [3, 0, 9] --> # 13 becomes 3, 10 becomes 0 and 19 becomes 9
       [3, 9] 
        [12]

The last number is the only one which can be composed by more than one digit. We only need the output of the final result: results = [11] or result = [12]. This is what I have tried so far:

def sum_triangle(numbers):
    
    if len(numbers) == 1:
        return (numbers)
        
    else:
        x = numbers
        while len(x) > 1:
            new_list = [a+b for a,b in zip(x[::2], x[1::2])]
            if len(x) % 2: new_list.append(numbers[-1])
            
    return new_list

Solution

  • Your while loop never changes x, so if the while condition is true once, it will always be true - an infinite loop.

    Instead of using three list variables (numbers, x, new_list), only use one list variable. Also, when you do a+b, first "trim" those numbers to their last digit, using %10.

    Here is how it could work:

    def sum_triangle(numbers):
        while len(numbers) > 1:
            last = numbers[-1] if len(numbers) % 2 else None
            numbers = [a % 10 + b % 10 for a, b in zip(numbers[::2], numbers[1::2])]
            if last is not None: 
                numbers.append(last)
                
        return numbers
    
    
    lst = [1, 5, 8, 13, 4]
    print(sum_triangle(lst))  # [11] 
    lst = [1, 12, 7, 3, 15, 4]
    print(sum_triangle(lst))  # [12]