加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

我正在编写嵌套的while循环,这些循环越来越不切实际(> 12个嵌

发布时间:2020-12-17 17:40:45 所属栏目:Python 来源:网络整理
导读:我有一些代码本质上会增加一个非常大的数字,我有一些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*

我有一些代码本质上会增加一个非常大的数字,我有一些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

这会打印出我想要的数字列表,以基数3表示时,最长为4位数字.
我实际上需要增加20位长数字,并且我编写的嵌套while循环越来越嵌套的代码.我相信Python在可以嵌套多少层上有一个限制,但是使用递归还必须有更好的方法吗?

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

最佳答案
没错,Python中嵌套的for循环是有限制的.我认为大约是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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读