【问题标题】:How to avoid to manually set the initial value of a variable in a recursive function?如何避免在递归函数中手动设置变量的初始值?
【发布时间】:2016-10-07 21:17:08
【问题描述】:

我为 Euler 项目 5 找到了这个解决方案(可以被 1 到 20 的所有数字整除的最小正数是多少?),其中整数值的可变范围可以除以:

def Euler5(start, end, counter):
    x = counter
    while start <= end:
        if x%counter == x%start:
            return Euler5(start+1, end, x)
        else:
            x += counter
    return x

但是,我必须手动将计数器设置为最小整数值(初始 counter = start 值)。有没有办法自动执行此操作并维护算法?

【问题讨论】:

    标签: python


    【解决方案1】:

    如果我的理解正确,您希望 counter == start 用于初始呼叫,而无需在首次呼叫中手动指定 counter

    为此,您可以将counter 设置为默认值None 并在函数开始时进行检查,如果是这种情况,请将counter 设置为适当的值:

    def Euler5(start, end, counter=None):
        if counter is None:
            counter = start
    
        x = counter
        while start <= end:
            if x % counter == x % start:
                return Euler5(start+1, end, x)
            else:
                x += counter
        return x
    

    【讨论】:

    • 如果情况确实如此,我将不胜感激。 ;)
    • 谢谢,非常感谢。
    猜你喜欢
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    • 2021-11-10
    • 1970-01-01
    • 2017-09-29
    • 1970-01-01
    • 1970-01-01
    • 2015-04-15
    相关资源
    最近更新 更多