# Palindrome finder [closed]

So I tried the brute force method after visiting https://www.programiz.com/python-programming/examples/palindrome on palindromes.

Any comment on how I can improve my coding will be much appreciated.

t=[]
def is_palindrome(x)
if list(str(x)) == list(reversed(str(x))):
t.append(x)
else:
pass

for i in range(100, 999):
for j in range(100, 999):
is_palindrome(i*j)
print(max(t))

• Please verify that the code works, and that what you have posted is exactly what you have been running. – 200_success Nov 27 '16 at 21:47
• also, do some searching: here is one – Edwin van Mierlo Nov 28 '16 at 11:57

Put it in a function!

def main():
for i in range(100, 999):
for j in range(100, 999):
is_palindrome(i*j)
print(max(t))

if __name__ == '__main__':
main()


you save yourself possible future headaches if you pick up this habit. When python imports a file, it will run the code in it, if not protected like this.

Maybe remove some casting,

if list(str(x)) == list(reversed(str(x))):


to this:

if str(x) == "".join(reversed(str(x))):


There is always a better way, then to use a global list, your t list is a global list. You are on the right track when defining a very clear is_palindrome function, but instead:

def is_palindrome(x):
if str(x) == "".join(reversed(str(x))):
return True
...

def main():
palindromes = []
for i in range(100, 999):
for j in range(100, 999):
if is_palindrome(i*j):
palindromes += [i*j]
...


This:

else:
pass


does not do anything and you should remove it.

Good work writing your code! a refactoring of it could look like this:

def is_palindrome(x):
if str(x) == "".join(reversed(str(x))):
return True

def main():
palindromes = []
for i in range(100, 999):
for j in range(100, 999):
if is_palindrome(i*j):
palindromes += [i*j]
print(max(palindromes))

if __name__ == '__main__':
main()


Well. Actually it's much slower to approach this problem in this way. Instead you could simply generate the palindromes, from max 999999 down to 100001 and the largest you find, will be the sought number.

that would look something inline with:

def find_palindrome():
for part in range(999, 99, -1):
palindrome = int("{}{}".format(part, str(part)[::-1]))
if check_divisability(palindrome):
return palindrome


leaving a mear 900 numbers to check, instead of checking all 899*899 possible numbers.