[Tutor] Re: reverse a number (was no subject)

Christopher Smith csmith@blakeschool.org
Thu, 22 Aug 2002 11:05:03 -0500


>--On Friday, August 9, 2002 5:39 PM +0530 Anand Ramakrishna 
><anandrs@hexaware.com> wrote:
>>     I am having a strange problem with my python code for reversing a
>> number. I tried it on a few combinations and works fine with most of
>them
>> except when the number starts in '1'. If I give input as 123 it reverses
>> and displays as 442. If I give input as 12 it reverses and displays as
>> 12. Where as if I give any other number, it reverses properly and
>> displays the correct result. The code is pasted below.
>
>I don't know what's wrong with the math in your attempt.  I didn't try to 
>figure it out, as it sounds like this problem is more easily solved using 
>strings:
>
>
>
>print 'This program accepts a number and then reverses it'
># The int() here may be unneccessary as we convert back to a string next,
># but it does help remove nondigits and leading zeroes.
>number = int(raw_input("Enter a number = "))
>
>numString = str(number)
>
># There's probably a more clever way to do this part.

How about converting the number to a list and then reversing the elements
now:

	m=list(str(int(number)))
	m.reverse()
	numString=''.join(m) #this is your reversed number as a string
>
>newnumString = ''
>for n in numString:
>  newnumString = n + newnumString
>
>newnum = int(newnumString)
>print 'The reversed number is ', newnum