In your check_palindrome
function you can directly return the result of the comparison:
def check_palindrome(s):
"""Checks whether the given string is palindrome"""
return s == s[::-1]
As @RobAu said in the comments, you should keep only the current maximum product, instead of building a (potentially very large) list of all products.
You can also reduce the number of products you need to check by realizing that if you checked 999*998
, you don't need to check 998*999
. This can be achieved by letting the inner loop start at i
.
max_product = 0
for i in range(999, 900, -1):
for j in range(i, 900, -1):
product = i * j
if check_palindrome(str(product)):
max_product = max(max_product, product)
print "i =", i, "j = ", j, "for", product
print max_product
Note that Python has an official style-guide, PEP8, which recommends using whitespace to separate operators and after commas in lists (including argument lists).
As a final step, I would make this a function that returns its result, instead of printing it:
def get_max_three_digit_product():
max_product = 0
for i in range(999, 900, -1):
for j in range(i, 900, -1):
product = i * j
if check_palindrome(str(product)):
max_product = max(max_product, product)
return max_product
This makes the code more re-usable, in case you ever need it again.
You can execute it under a if __name__ == "__main__":
guard, which allows you to import this function from another script, without executing the function.
if __name__ == "__main__":
print get_max_three_digit_product()
break
your inner loop after the first palindrome for a given (i, j) pair - you are counting towards lower numbers, and any subsequent palindrome of the formi * (j - m)
will be lower than your currenti * j
. Likewise, if your first discovered palindrome is less than the current max palindrome,break
because it won't get bigger. \$\endgroup\$