1
\$\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)))
\$\endgroup\$

1 Answer 1

1
\$\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)]
\$\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

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.