[Tutor] Reversing digits of number (WAS Re: (no subject))
Prahlad Vaidyanathan
slime@vsnl.net
Sat, 10 Aug 2002 07:00:33 +0530
Hi,
On Fri, 09 Aug 2002 Anand Ramakrishna spewed into the ether:
> Hi,
> 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.
Well, your logic is a *little* flawed. Read below ..
[-- snippity --]
> print 'This program accepts a number and then reverses it'
> number = int(raw_input("Enter a number = "))
> temp_var = 0
>
> while (number/10) > 1 :
^^^^
Here is your problem. This should be ">= 1". For example,
when you enter "12", look at what happens.
"""
>>> number = 12
>>> number/10
1
>>> (number/10) > 1 ## False
0
>>> (number/10) >= 1 ## True
1
>>>
"""
Therefore, by your method, if the 1st digit is exactly "1",
then the program comes out of the while loop, and thus the
"number" now holds the 1st *and* the 2nd digit (12, in this case)
when it enters the else loop.
Thus, you get results like so :
Input: 123 => Output: ((3*10) + 12) = 42
Input: 1557 => Output: ((75*10) + 15) = 765
HTH,
pv.
--
Prahlad Vaidyanathan <http://www.symonds.net/~prahladv/>
Rich bachelors should be heavily taxed. It is not fair that some men
should be happier than others.
-- Oscar Wilde