繁体   English   中英

使用 Python(仅使用一个数字)的三角形数字总和?

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

给定如下列表:[1, 5, 8, 13, 4],我们想要找到两个连续数字的总和,如下所示。 我们应该考虑到,如果列表中的数字超过一位,则需要将其更改为最后一位 position(最右边)中的数字。 另外,我们应该考虑如果列表的总数是奇数,则最后一个数字会自动添加到列表中:

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

或者

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

最后一个数字是唯一可以由多于一位数字组成的数字。 我们只需要最终结果的output:results = [11] or result = [12]。 到目前为止,这是我尝试过的:

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

你的while循环永远不会改变x ,所以如果while条件一次为真,它将永远为真 - 一个无限循环。

不使用三个列表变量( numbersxnew_list ),而是只使用一个列表变量。 此外,当您执行a+b时,首先使用%10将这些数字“修剪”到最后一位。

这是它的工作原理:

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]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM