簡體   English   中英

如果給定一個整數列表和一個名為 x 的數字,如何遞歸返回列表中每個第 x 個數字的總和

[英]How to if given a list of integers and a number called x, return recursively the sum of every x'th number in the list

那么,如果給定一個整數列表和一個名為 x 的數字,如何遞歸返回列表中每個第 x 個數字的總和。

在此任務中,“索引”從 1 開始,因此如果x = 2nums = [2, 3, 4, -9] ,則 output 應為-6 (3 + -9)。

X 也可以是負數,在這種情況下,索引從列表的末尾開始,請參見下面的示例。

如果x = 0 ,則總和也應為0

例如:

print(x_sum_recursion([], 3))  # 0
print(x_sum_recursion([2, 5, 6, 0, 15, 5], 3))  # 11
print(x_sum_recursion([0, 5, 6, -5, -9, 3], 1))  # 0
print(x_sum_recursion([43, 90, 115, 500], -2))  # 158
print(x_sum_recursion([1, 2], -9))  # 0
print(x_sum_recursion([2, 3, 6], 5))  # 0
print(x_sum_recursion([6, 5, 3, 2, 9, 8, 6, 5, 4], 3))  # 15

我一直在嘗試這樣做 function 連續 5 個小時!!!

想看看其他人會如何解決這個問題。

這是我想出的最好的。

def x_sum_rec_Four(nums: list, x: int) -> int:
    if len(nums) == 0:
        return 0
    elif len(nums) < x:
        return 0
    elif x > 0:
        i = x - 1
        return nums[i] + x_sum_rec_Four(nums[i + x:], x)
    elif x < 0:
        return x_sum_rec_Four(nums[::-1], abs(x))

我對這個遞歸的問題是完成返回應該是:

if len(nums) < x:
    return nums[0]

但這會傳遞([2, 3, 6], 5)) -->> 2之類的東西,而它應該是 0。

如果您確實需要遞歸執行此操作,您可以在每次調用之前從列表中彈出 x-1 個元素,請遵循以下評論:

def x_sum_recursion(nums, x):
    # if x is negative, call the function with positive x and reversed list
    if x < 0:
        return x_sum_recursion(nums[::-1], abs(x))
    # base case for when x is greater than the length of the list
    if x > len(nums):
        return 0
    # otherwise remove the first x-1 items
    nums = nums[x-1:]
    # sum the first element and remove it from the next call
    return nums[0] + x_sum_recursion(nums[1:], x)

print(x_sum_recursion([], 3))  # 0
print(x_sum_recursion([2, 5, 6, 0, 15, 5], 3))  # 11
print(x_sum_recursion([0, 5, 6, -5, -9, 3], 1))  # 0
print(x_sum_recursion([43, 90, 115, 500], -2))  # 158
print(x_sum_recursion([1, 2], -9))  # 0
print(x_sum_recursion([2, 3, 6], 5))  # 0
print(x_sum_recursion([6, 5, 3, 2, 9, 8, 6, 5, 4], 3))  # 15

但是,您可以通過一種簡單且 Pythonic 的方式來完成它:

print(sum(nums[x-1::x] if x > 0 else nums[x::x]))

解釋:

您使用nums[start:end:increment]對列表進行切片,當您將結尾留空時,它將從起始 position 切片到列表末尾,並按指定的增量遞增

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM