Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/298.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 我正在编写嵌套的while循环,而这些循环的深度越来越深(>;12个嵌套循环),如何递归地编写它?_Python_Recursion - Fatal编程技术网

Python 我正在编写嵌套的while循环,而这些循环的深度越来越深(>;12个嵌套循环),如何递归地编写它?

Python 我正在编写嵌套的while循环,而这些循环的深度越来越深(>;12个嵌套循环),如何递归地编写它?,python,recursion,Python,Recursion,我有一些代码基本上增加了一个非常大的数字,我有一些python代码可以很好地处理较小的数字 def test_loop(): base = 3 # increment number for a in range(0,2): b = a while b < base: c = b while c < base: d = c

我有一些代码基本上增加了一个非常大的数字,我有一些python代码可以很好地处理较小的数字

def test_loop():

    base = 3

    # increment number
    for a in range(0,2):
        b = a

        while b < base:
            c = b

            while c < base:
                d = c

                while d < base:

                    n = (d + c*base**1 + b*base**2 + a*base**3)
                    print n

                    d += 1
                c += 1
            b += 1
def test_loop():
基数=3
#增量数
对于范围(0,2)内的a:
b=a
而b
这会打印出一个我想要的数字列表,当以3为基数表示时,长度可达4位。 实际上,我需要达到20+位数的长度,我已经编写了嵌套的代码,而循环的嵌套越来越多。我相信Python对嵌套的可能级别有限制,但一定有更好的方法使用递归

示例结果 0 1. 2. 4. 5. 8. 13 14 17 26 40 41 44
53

您应该创建一个函数并抽象每个嵌套。然后对后面的组合求和

def函数(g、基数、数字):
返回g*基**位

您不应该在python上使用递归,即使使用尾部调用函数,它也不适合。如果您仍然想这样做,请使用累加器。

您是对的,Python中嵌套的
循环有一个限制。我想大约是20,所以你的解决方案不起作用。但是,即使限制更大,您也希望使用递归使代码更清晰、简洁、更灵活。以下是递归如何解决您的问题:

def list_special_numbers(base, digits, starting_digit=0, partial_sum=0):
    if digits == 1:
        for i in range(starting_digit, base):
            print(partial_sum + i)
    else:
        for i in range(starting_digit, base):
            list_special_numbers(base, digits-1, i, partial_sum + i*(base**(digits-1)))

# *** Usage examples ***

# print the list of desired numbers up to 20-ternary-digit numbers
list_special_numbers(3,20)

# print the list of desired numbers up to 30-ternary-digit numbers
list_special_numbers(3,30)

# print the list of desired numbers up to 30-binary-digit numbers
list_special_numbers(2,30)

# print the list of desired numbers up to 3-decimal-digit numbers
list_special_numbers(10,3)

对于>12个嵌套循环,递归地编写循环是次要考虑的问题。请查看
itertools
模块,可能是
itertools。产品
就是您想要的。如果只深入几百层,Python中的递归是绝对好的。对于OPs的问题,递归是一个优雅而快速的解决方案。如果你愿意的话,看看我的答案。加里的解决方案确实对我有效,但我更喜欢这个解决方案。哇,刚刚用一些更大的数字进行了测试,速度非常快。你有没有用30位数字尝试过Gary的解决方案?:)