+ 1
Python palindrome challenge.
I'm doing a challenge. I have to find the largest palindrome (explained below) from the product of 3-digit numbers. Palindrome - is a word/number that reads the same in forward/backward direction. e.g. 0110 , madam. The largest 2-digit palindrom is 9009. Resulted in a calculation of: 91*99 = 9009. I have the following code, any suggestions? https://code.sololearn.com/cnqcPaOMXbpK/?ref=app
10 Answers
+ 7
Just a "different" school of thought...
You could save time and only compare half.
If the first half of the word matches the first half of the reversed word, it's a match. Comparing the whole thing is redundant.
+ 6
Lamron ,
i did some tests in case of performance and memory consumption. see some comments and the code in the file:
https://code.sololearn.com/c5Sbq5KqDdZW/?ref=app
+ 6
Ausgrindtube ,
how much time can be saved by applying your idea? did you do any tests for this?
+ 3
Slice in reverse is m[ : : -1]
+ 3
Lothar I'm way too lazy to do anything actually useful like that, sorry 😅
I imagine on most machines it wouldn't save much time nor computing resources, how long can a word be, right?
+ 2
Simple mistake, but changes a lot....
Thanks Jayakrishna 🇮🇳
+ 1
Lothar , yes your code is optimised well indeed, and I see how you did it. Thanks for showing optimised alternative
0
In your code, you are trying to check if the entire string of the product is equal to its reversed version, instead of checking if the string is the same forwards and backwards. I would suggest you use string slicing to reverse the string, and then compares it with the original string. If they are the same, you can then add it to the list.
Also, i found creating two lists "ls" and "new" then reiterating through both as redundant. you can use the same range and make a nested "for loop" and after the loop .. the maximum max(poly) will be the largest palindrome
`max` is a builtin function
0
Thanks Mirielle
0
I took a rest though about it, tried again and it worked. Thanks for guidance!