Home > database >  how to resolve this "inf" problem with python code
how to resolve this "inf" problem with python code

Time:11-25

i have a problem with this python code for inverting a Number like Nb = 358 ---> inv = 853 but in the end i got 'inf' msg from the prog , and its runs normally in C language

def envers(Nb):
 inv = 0
 cond = True
 while cond:
    s = Nb % 10
    inv = (inv*10)  s
    Nb = Nb/10
    if Nb == 0:
        cond = False
 return inv

data = int(input("give num"))
res = envers(data)
print(res)

CodePudding user response:

This is likely much easier to do via string manipulation, which has a friendly and simple syntax (which are a major reason to choose to use Python)

>>> int(input("enter a number to reverse: ")[::-1])
enter a number to reverse: 1234
4321

How this works

  • input() returns a string
  • strings are iterable and [::-1] is used to reverse it
  • finally convert to an int

Add error checking to taste (for example to to ensure you really received a number)

CodePudding user response:

When you set

Nb = Nb / 10

Nb becomes a float (say 1 -> 0.1) and will be able to keep being divided until it reaches a certain limit.

By that point, your inv value will reach python's limits and become 'inf'.

Replacing this line with

Nb = Nb // 10

using Python's builtin integer division will fix the issue.

CodePudding user response:

Here is a simple implementation for a numerical approach:

def envers(Nb):
    out = 0
    while Nb>0:
        Nb, r = divmod(Nb, 10)
        out = 10*out   r
    return out


envers(1234)
# 4321

envers(358)
# 853

envers(1020)
# 201

Without divmod:

def envers(Nb):
    out = 0
    while Nb>0:
        r = Nb % 10
        Nb //= 10
        out = 10*out   r
    return out
  • Related