简体   繁体   中英

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

So, 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.

In this task "indexing" starts from 1, so if x = 2 and nums = [2, 3, 4, -9] , the output should be -6 (3 + -9).

X can also be negative, in that case indexing starts from the end of the list, see examples below.

If x = 0 , the sum should be 0 as well.

For example:

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

I have been trying to do this function for 5 hours straight!!!

Would like do see how someone else would solve this.

This is the best i have come up with.

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))

My problem with this recursion is that the finish return should be:

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

but that would pass things like ([2, 3, 6], 5)) -->> 2 when it should be 0.

If you really need to do it recursively, you could pop x-1 elements from the list before each call, follow the comments below:

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

However, you can do it in a one liner simple and pythonic way:

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

Explanation:

you slice the list using nums[start:end:increment] when you leave the end empty it slices from the starting position till the end of the list and increments by the increment specified

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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