+ 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

28th Jan 2023, 12:22 PM
Lamron
Lamron - avatar
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.
28th Jan 2023, 2:02 PM
Ausgrindtube
Ausgrindtube - avatar
+ 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
28th Jan 2023, 8:21 PM
Lothar
Lothar - avatar
+ 6
Ausgrindtube , how much time can be saved by applying your idea? did you do any tests for this?
28th Jan 2023, 8:25 PM
Lothar
Lothar - avatar
+ 3
Slice in reverse is m[ : : -1]
28th Jan 2023, 12:29 PM
Jayakrishna 🇮🇳
+ 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?
29th Jan 2023, 4:38 PM
Ausgrindtube
Ausgrindtube - avatar
+ 2
Simple mistake, but changes a lot.... Thanks Jayakrishna 🇮🇳
28th Jan 2023, 12:31 PM
Lamron
Lamron - avatar
+ 1
Lothar , yes your code is optimised well indeed, and I see how you did it. Thanks for showing optimised alternative
28th Jan 2023, 8:28 PM
Lamron
Lamron - avatar
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
28th Jan 2023, 12:35 PM
Mirielle
Mirielle - avatar
0
Thanks Mirielle
28th Jan 2023, 12:38 PM
Lamron
Lamron - avatar
0
I took a rest though about it, tried again and it worked. Thanks for guidance!
28th Jan 2023, 5:45 PM
Lamron
Lamron - avatar