How to rewrite a program to use recursion?

前端 未结 2 488
太阳男子
太阳男子 2021-01-28 02:46

Just started to deal with recursion - I don’t understand everything in it yet. I think that i don\'t use a basic conditional, but i don\'t have any idea how to write it. The pro

2条回答
  •  不思量自难忘°
    2021-01-28 02:53

    Maybe this approach can help you understand.

    It starts from the first element and sums the rest every x ones.

    That is my assumption, as you haven't provided an input and its desired output as an example.

    In case you need to start from the xth element the code can be easily modified, I leave it to you to experiment with it.

    def sum_elements(nums, x) -> int:
        if x>0 and x<=len(nums):
            return nums[0] + sum_elements(nums[x:], x)
        return 0
    
    lst = [1, 2, 3, 4, 5, 6]
    print(sum_elements(lst, 2))
    print(sum_elements(lst, 3))
    print(sum_elements(lst, 0))
    

    produces

    9
    5
    0
    

    Note: it just demonstrates recursion, but it's not optimal for a number of reasons.

    Also it discards negative values of x

提交回复
热议问题