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

Time:02-26

Can somebody point out why am I getting infinite loop in this? I mean it shows error for maximum recursion depth reached? For value of '1' it shows correct output.

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)))

CodePudding user response:

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))

this is your code where check is returning a value when n==1 if not check(beautiful(n)) but beautiful(n) returns value which is which is either 1 greater than n or removes 0 from end if exists.

for example if n=5 is passed it gets returned when value of n reaches 10 cause 0 is removed from end and at n==1 it gets returned. But as u mentioned n ranges up-to 10^9 if at all a number is something like 1234567 then it recursion stack gets piled up if at all n value reaches to 1 before recursion depth limit is exceeded it works fine if not u get the error recursion depth reached. And recursive depth has different default values eg:-2000

if you want to change ur recursive depth limit follow this

in this case using interative solution is recommended.

iterative solution!!:

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))

CodePudding user response:

I think you are assuming that new.rstrip('0') modifies the value of new. That is not the case:

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

You can fix your issue by changing this line to new=new.rstrip('0').

You may still get recursion-depth errors for sufficiently large values.

CodePudding user response:

Unless I've completely misunderstood this, it has been over-complicated in the extreme. It's as simple as this:

Note: no recursion, no string manipulation

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

Output:

[12, 13, 14, 15, 16, 17, 18, 19, 2, 3, 4, 5, 6, 7, 8, 9, 1]
  • Related