Home > Back-end >  Why does my number reverser function produce an infinite loop
Why does my number reverser function produce an infinite loop

Time:09-29

Whenever i try print the number reverser function i always get an infinite loop,instead of my expected output 54321. Can someone help find the problem? Thanks.

def order(num):
    x=str(num)
    if x==False:
        return None
    else:
        return order(x[1:]) (x[0])
print (order(12345))

CodePudding user response:

Welcome to your community.
There are some problems with your code:
First:
A string never will be equal to False.
for instance:
'0' is not equal to False.
'' is not equal to False.
Second:
You cannot add a String to None.
This Error will be thrown: TypeError: can only concatenate str (not "NoneType") to str


Modify your code like this:

def order(num):
    x=str(num)
    if x=='':
        return ''
    else:
        return order(x[1:]) (x[0])
print (order(12345))

Tip 1: A string can be equal to '' (empty string).

CodePudding user response:

In your function, you compare the string x with the boolean False. This is not a correct way to test whether string x is an empty string or not.

In addition, if string x is empty, then you shouldn't return None, but an empty string: reversing an empty string should logically return an empty string.

Here I present two ways to fix your function, which I implemented under the names reverse0 and reverse1. I also present a few other alternatives to achieve the same result using python features, under the names reverse2 to reverse6. Finally I present three other ways to reverse nonnegative integers, under the names reverse7 to reverse9.

def reverse0(num):
  x = str(num)
  if len(x) == 0:
    return ''
  else:
    return reverse0(x[1:])   x[0]
  
def reverse1(num):
  x = str(num)
  if not x:
    return ''
  else:
    return reverse1(x[1:])   x[0]

def reverse2(num):
  return str(num)[::-1]

def reverse3(num):
  return ''.join(reversed(str(num)))

def reverse4(num):
  x = str(num)
  return ''.join(x[len(x)-1-i] for i in range(len(x)))

def reverse5(num):
  x = str(num)
  return ''.join(x[-i] for i in range(1, len(x) 1))

def reverse6(num):
  y = ''
  for c in str(num):
    y = c   y
  return y

# reverse7 only works for nonnegative integers
def reverse7(num):
  if num < 10:
    return str(num)
  else:
    return str(num % 10)   reverse7(num // 10)

# reverse8 only works for nonnegative integers
def reverse8(num):
  l = []
  while num > 9:
    l.append(num % 10)
    num = num // 10
  l.append(num)
  return ''.join(str(d) for d in l)

# reverse9 only works for nonnegative integers
# reverse9 returns an int, not an str
def reverse9(num):
  y = 0
  while num > 0:
    y = 10 * y   (num % 10)
    num = num // 10
  return y

Relevant documentation:

  • Related