简体   繁体   English

如何用递归求和参数列表?

[英]how to sum a list of arguments with recursion?

I am trying to write a function that takes any number of arguments and then sums them using recursion ( I am not using the built in sum function. I am assuming arguments will be int. ) 我试图编写一个函数,该函数接受任意数量的参数,然后使用递归求和(我未使用内置的sum函数。我假设参数将为int。)

But my base case doesn't stop it from recursing! 但是我的基本情况并不能阻止它再次发生! Any hints? 有什么提示吗?

def sum_all(*args):
 if args == ():
    return 0
 else:
    return args[0] + sum_all(args[1:])

You need to expand the args in your recursion, and not args would be sufficient for the test: 您需要在递归中扩展args,而not args不足以进行测试:

def sum_all(*args):
    if not args:
        return 0
    return args[0] + sum_all(*args[1:])
                             ^

Python 3 also added some new syntax that allows you to unpack *args , eg: Python 3还添加了一些新语法,使您可以解压缩*args ,例如:

def sum_all(*args):
    if not args:
        return 0
    a, *b = args
    return a + sum_all(*b)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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