python - How to write a function that adds numbers in a list by calling itself? -
i'm trying write function adds numbers in list calling in python. here's example of mean:
def factorial(n): if n == 1: return 1 else: return n * factorial(n-1)
how use find sum of list?
nums = [1, 3, 2, 8, 9] def rec_sum(nums): if not nums: return 0 return nums[0] + rec_sum(nums[1:]) >>> rec_sum(nums) 23
you in 1 line:
def rec_sum(nums): return nums[0] + rec_sum(nums[1:]) if nums else 0
to avoid shallow copies of list being made nums[1:]
on each call can more efficient:
def rec_sum(nums, i=0): if >= len(nums): return 0 return nums[i] + rec_sum(nums, i+1)
it's fun use y-combinator
>>> y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args))) >>> rec_sum = lambda f: lambda nums: nums[0] + f(nums[1:]) if nums else 0 >>> y(rec_sum)(nums) 23
Comments
Post a Comment