简体   繁体   中英

Finding the largest palindrome of the product of two 3-digit numbers in Python

So the challenge I'm trying to solve is to find the largest palindrome made from the product of two 3-digit numbers. I'm new to Python and so my code is not elegant or refracted yet, but there is a logical error that I can't seem to find.

def ispalindrome(n):
    rev_n = str(n)[::-1]
    if n == rev_n:
        return True
    else:
        return False


first_num = 100
second_num = 100
mylist=[]
while first_num < 1000:
    while second_num < 1000:
        item = first_num * second_num
        mylist.append(item)
        second_num += 1
    second_num = 100
    first_num +=1
# print (mylist)
num_as_string = []
for i in mylist:
    i = str(i)
    num_as_string.append(i)
print("Total products of two 3-digit numbers: {}").format(len(num_as_string))
print("-----------------------------------------------------")

def convert_to_num_list(string_list):
    new_num_list = []
    item = int(string_list)
    new_num_list.append(item)
    return new_num_list



palindrome_list = []

for j in num_as_string:
    if ispalindrome(j) == True:
        palindrome_list.append(j)
        palindrome_list.sort()
        # print(palindrome_list)
        x = convert_to_num_list(j)
        largest_palindrome = max(x)

print("Total palindroms of product of two 3-digit numers: {}").format(len(palindrome_list))

print("Largest palindrome = {}").format(largest_palindrome)

The problem is that I'm getting the largest palindrome as 580085, which is 995*583 but is NOT the largest palindrome. I believe the largest palindrome is 906609, which is 993*913, but my code is not finding this. Can anyone help me with the flaw in my logic?

Your code does a lot of unnecessary conversion between numbers and strings, which made the error hard to find. The only place in the code that needs a string representation is when determining if the number is a palindrome or not. So that should be the only place that the code does the conversion.

The logic error is in your function convert_to_num_list() . It takes a string representation of one number and returns a 1-list containing that number. So, "123321" gets returned as [123321] . You then take the max() of that 1-list, which is always the value that was passed to convert_to_num_list() . So the code never keeps the largest value because if a smaller value comes in later it will be overwritten. The code reports 995*583 as the largest because it comes in later than 993*913 , which in turn is because 995 > 993 .

You can fix that error with an if statement, but the program is overcomplicated and may well contain other bugs. I recommend reducing the code to the essential task of producing the largest palindrome, without printing out the intermediate results, because the simpler the code the easier it is to see a logic error.

def ispalindrome(n):
    return str(n) == str(n)[::-1]

mylist=[]
for first_num in range(100,1000):
    for second_num in range(100,1000):
        item = first_num*second_num
        if ispalindrome(item):
            mylist.append(item)
print(max(mylist))

This gives your expected answer:

906609

Here is a function for finding the largest palindrome of the product of two 3-digit numbers that I found in stackoverflow.

Link to what i found- https://stackoverflow.com/a/7460573

def is_pal(c):
       return int(str(c)[::-1]) == c

   maxpal = 0
   for a in range(999, 99, -1):
       for b in range(a, 99, -1):
           prod = a * b
           if is_pal(prod) and prod > maxpal:
               maxpal = prod

   print maxpal
n1=999
n2=999
k=0
sl=[]
while n1>1:
  count=n1
  while count>=1:
    result=n1*count
    res=str(result)
    res1=res[::-1]
    if (res==res1):
      sl.insert(k,result)
      k+=1
    count=count-1
  n1=n1-1
print("largest pelindrom of 3 digit product is is %d" %(max(sl)))
palin=[]

for a in (range(1,1000)):
    for b in (range(1,1000)):
        d = a*b
        d=str(d)
        if len(d)>5: 
            if d[0]==d[5]:
                    if d[1]==d[4]:
                        if d[2]==d[3]:
                            palin.append(d)
palin.sort()
print(palin[len(palin)-1])

Using List comprehension can reduce the lines of code but i'll give an alternate option so that it's more readable.

List_of_palindromes = [i*j for i in range(100,1000) for j in range(i,1000) if str(i*j)==str(i*j)[::-1]]
print(max(List_of_palindromes))

More Readable form

List_of_palindromes = []
for i in range(100,1000):
    for j in range(100,1000):
        if str(i*j)==str(i*j)[::-1]:
            List_of_palindromes.append(i*j)
print(max(List_of_palindromes))

Check this out..! This can be shortened but its better understandable this way(for beginners).

    l = list(range(100, 1000))
    m = list(range(100, 1000))
    prod_max = 0

    def is_palindrome(num):
      temp = num
      rev=0
      while num > 0:
        div = num%10
        rev = rev*10 + div
        num = num //10
        if rev == temp:
          return True
        else:
          return False

    for i in range(len(l)):
      for j in range(len(m)):
        prod = l[i]*m[j]
        if is_palindrome(prod) == True:
          if prod > prod_max:
            prod_max = prod
            num1 = l[i]
            num2 = m[j]
    print(f'{prod_max} the product of {num1} and {num2} is a palindrome')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM