2
\$\begingroup\$

I solved the HackerRank version of the Largest palindrome problem (similar to Project Euler 4) in Python:

Find the largest palindrome made from the product of two 3-digit numbers which is less than N, where 101101 < N < 1000000.

How can I make this more efficient? My solution keeps timing out.

Here is the Code:

# Find the Largest palindrome made from two three digit numbers which are less than N
# Get the input and store it in an array
def get_input():
 limit = int(input())
 limits = []
 for _ in range(limit):
 limits.append(int(input().strip()))
 return limits
# Check if palindrome or not
def is_palindrome(num):
 if str(num) == str(num)[::-1]:
 return True
 else:
 return False
# Find the Largest Palindrome
def largest_palindrome(num):
 largest = 0
 for i in range(2,999+1):
 for j in range(i+1 , 999+1):
 prod = i * j
 if is_palindrome(prod) and prod > largest and prod < num:
 largest = prod
 return largest
# Get the Limits
limits = get_input()
for limit in limits:
 print(largest_palindrome(int(limit)))
200_success
146k22 gold badges190 silver badges479 bronze badges
asked Oct 29, 2016 at 2:33
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

Look at my previous answer

  • palindrome is divisible by 11
  • i and j can be only odd
  • reverse loops 999 -> 1 and 999 -> i - 1 - first found palindrome less than n is our palindrome

Simplify code

str(num) is expensive, do it once

def is_palindrome(num):
 snum = str(num)
 return if snum == snum[::-1]

Instead of prod > largest and prod < num You can write num > prod > largest

Use list comprehension

limits = [int(input().strip()) for _ in range(limit)]
answered Oct 29, 2016 at 5:36
\$\endgroup\$
1
  • 1
    \$\begingroup\$ To be noted: All palindromes with an even number of digits are divisible by 11. \$\endgroup\$ Commented Oct 29, 2016 at 6:22

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.