为什么对于 1 到 10**9 范围内的任何输入值,此代码都会出现无限循环?

Why am I getting infinite loop for the this code for any input value of range 1 to 10**9?

有人可以指出为什么我会在其中出现无限循环吗?我的意思是它显示达到最大递归深度的错误? 对于“1”的值,它显示正确的输出。

def beautiful(n):
    new=str(n+1)
    new.rstrip('0')
    return int(new)
def check(n):
    if n==1:
       temp.extend(list(range(1,10)))
       return
    else:
       temp.append(n)
       return check(beautiful(n))
    
n=int(input())
temp=[]
check(n)
print(len(set(temp)))
def beautiful(n):
    new=str(n+1)
    new.rstrip('0')
    return int(new)
def check(n):
    if n==1:
       temp.extend(list(range(1,10)))
       return
    else:
       temp.append(n)
       return check(beautiful(n))

这是你的代码,当 n==1 if not check(beautiful(n)) but beautiful(n) returns 值是 1 大于 n 或如果存在则从末尾删除 0。

例如,如果 n=5 被传递,它会在 n 的值达到 10 时返回,因为 0 从末尾删除,而在 n==1 时它会被返回。但是正如你提到的 n 范围 up-to 10^9 如果一个数字是 1234567 那么它递归堆栈会堆积起来如果在超过递归深度限制之前所有 n 值达到 1 它工作正常如果不是你得到达到的错误递归深度。并且递归深度有不同的默认值例如:-2000

如果你想改变你的递归深度限制follow this

在这种情况下,建议使用交互式解决方案。

迭代解决方案!!:

n=11
temp=[]
while 1:
    if n==1:
        temp.extend(list(range(1,10)))
        break
    else:
        temp.append(n)
        n=str(n+1)
        n=n.rstrip('0')
        n=int(n)
        
print(len(temp))

我认为您假设 new.rstrip('0') 修改了 new 的值。事实并非如此:

str.rstrip([chars]) Return a copy of the string with trailing characters removed.

您可以通过将此行更改为 new=new.rstrip('0') 来解决您的问题。

对于足够大的值,您可能仍会遇到 recursion-depth 个错误。

除非我完全误解了这一点,否则它已达到 over-complicated 的极限。就这么简单:

注意:没有递归,没有字符串操作

def check(n):
    result = []
    while n > 1:
        if (n := n + 1) % 10 == 0:
            n //= 10
        result.append(n)
    return result
print(check(17))

输出:

[18, 19, 2, 3, 4, 5, 6, 7, 8, 9, 1]