[Tutor] project euler #4
DL Neil
PyTutor at danceswithmice.info
Mon May 11 07:17:03 EDT 2020
On 11/05/20 9:04 PM, Sibylle Koczian wrote:
> Am 11.05.2020 um 10:01 schrieb Alan Gauld via Tutor:
>> On 11/05/2020 04:46, Nitish Kumar wrote:
>>> i am an ansolute noob at python...i started teaching myself a while back
>>> please review my code....and please point out the errors...
>>
>>> def isPalindrome(n):
>>> temp = n
>>> rev = 0
>>> while(n > 0):
>>> digit = n % 10
>>> rev = rev*10 + digit
>>> n = n // 10
>>
>> This loop should never end since n will always be
>> greater than zero, albeit becoming very small.
>>
> Wrong. The division is integer division, of course n will be zero. This
> might be a little faster using divmod(n, 10) - and learning about divmod
> will often be useful. But the function is quite correct.
To solve problems of this nature add 'debug print' calls, to keep track
of pertinent values, eg before modifying "n" in the while loop, add:
print( "Loop values:", n, digit, rev )
The debug-print will immediately demonstrate if the code is working,
step-by-step (loop-by-loop?) - or not, and thus allow you to debug on
your own.
That said, this algorithm is attempting to solve the problem in a
mathematical fashion. It will only work with numbers.
Many play with palindromes that are words, eg everyone's ?favorite?
band: ABBA.
If, the input number were converted to a string (it might even have
originally been input as a string?), then the process of proving a
palindrome becomes an exercise in string indexing or slicing - depending
upon whether each character is considered in-turn, or whether the
algorithm slices the word in half, reverses the characters in one half
and then tries for equality with the other...
(study operations on strings of characters)
At which point, you would have a more flexible solution that works for
'both' input types, cf only 'numbers'!
As a newbie, you may like to follow-up on the (Computer Science)
definition of "polymorphism"...
Please note: I am not saying that your approach is "wrong", will never
work, nor that it is inferior or "insufficient" for your objectives!
--
Regards =dn
More information about the Tutor
mailing list