Amir Chazan February 2016

writing a function that return the reversed number

I am trying to write a Python function that get a number as input and returns its reversed number as output. for example: 1234 returns 4321.

this is what I try, but it return only ''

def reverse(num):
  L=[]
  x=str(num)
  L1=list(x)

  for i in L1:
    L.insert(0,i)
  print 'the reversed num is:'

  x=''
  for i in L:
    x.join(i)
    return x

any ideas?

Answers


Alexey Astahov February 2016

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

or one line:

lambda x: str(x)[::-1]


timgeb February 2016

Well, the easy solution is this one:

>>> int(str(1234)[::-1])
4321

Your code can be fixed by changing the part

for i in L:
    x.join(i)
    return x

to

for i in L:
    x += i
return x

Alternatively, just replace that section by

return ''.join(L)

What was wrong with your code? Because of wrong indentation, you returned in the first iteration of the for loop. You never assigned a name to x.join(i) so the return value was lost. What you expected join to do I do not know.


Eamonn McEvoy February 2016

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

Reverse a string in Python


Julien Spronck February 2016

First, there is an easier way by converting to string, slicing the string and converting it back to a number.

def reverse(num):
    return int(str(num)[::-1])

Second, there are multiple errors in your code:

1) your return statement is in the loop, so it will return after the first iteration;

2) x does not change because x.join() creates a new string and does not modify the string x (which is immutable by the way)

3) no need to convert the string into a list since you can directly iterate over the string (for i in x: ...)

4) join() takes an iterator as an argument. No need for the second loop: return ''.join(L)


Rockybilly February 2016

Other users already gave good answers. Here is a different one, for study purposes.

num = 1234
print "".join(reversed(str(num)))
# 4321

You can convert to int afterwards.


Amir Chazan February 2016

thank you all for the helpful ideas.

here is my solution:

         def reverse(n):
            reverse=0
            while(n>0):
                    dig=n%10
                    reverse=reverse*10
                    reverse=reverse+dig
                    n=n/10
            return reverse

Post Status

Asked in February 2016
Viewed 3,484 times
Voted 12
Answered 6 times

Search




Leave an answer