[Tutor] project euler #4
Mats Wichmann
mats at wichmann.us
Mon May 11 14:08:14 EDT 2020
On 5/11/20 5:17 AM, DL Neil via Tutor wrote:
>
> 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'
So to Nitish, the OP: congratulations on taking on the project Euler
problems, they're really neat. You've also stumbled on an interesting
thing that sometimes happens with this list, and in fact any general
help forum.
The Euler problems are attempting to teach _mathematical_ concepts
(encouraging the use of a computer to assist), while where here on the
list tend to approach problems as ones of what are optimal Python
approaches. Just like DL Neil, I immediately thought of solving this by
using strings, which Python handles very easily. So this replacement
function works quite nicely, and teaches you nothing about mathematics -
was that your aim? Or was Python your aim?
def isPalindrome(n):
n = str(n).casefold() # eliminate any string case differences
return n == n[::-1]
the right-hand side n[::-1] steps backwards through the string giving
you a new string which is the reverse of the original (this syntax is
what is called "slicing"); if old and new are equal it's a palindrome
and the return will be True, else the return will be False.
since your problem is to find the largest, after you've collected the
list of palindromes, you can emit it with
print(max(palin))
More information about the Tutor
mailing list