簡體   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