简体   繁体   English

在Python中找到两个三位数乘积的最大回文

[英]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.所以我试图解决的挑战是找到由两个 3 位数字的乘积构成的最大回文数。 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.我是 Python 新手,所以我的代码还不够优雅或折射,但我似乎无法找到一个逻辑错误。

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.问题是我得到的最大回文数为 580085,即 995*583,但不是最大的回文数。 I believe the largest palindrome is 906609, which is 993*913, but my code is not finding this.我相信最大的回文数是 906609,也就是 993*913,但是我的代码没有找到这个。 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() .逻辑错误在您的函数convert_to_num_list() It takes a string representation of one number and returns a 1-list containing that number.它接受一个数字的字符串表示,并返回一个包含该数字的 1 列表。 So, "123321" gets returned as [123321] .因此, "123321"返回为[123321] You then take the max() of that 1-list, which is always the value that was passed to convert_to_num_list() .然后取那个 1-list 的max() ,它始终是传递给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 .代码报告995*583是最大的,因为它晚于993*913 ,而这又是因为995 > 993

You can fix that error with an if statement, but the program is overcomplicated and may well contain other bugs.您可以使用if语句修复该错误,但该程序过于复杂并且很可能包含其他错误。 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.这是一个函数,用于查找我在 stackoverflow 中找到的两个 3 位数字的乘积的最大回文数。

Link to what i found- https://stackoverflow.com/a/7460573链接到我发现的内容 - 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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 找到两个三位数的最大回文乘积:逻辑错误是什么? - Finding the largest palindrome product of two 3-digit numbers: what is the error in logic? 来自两个3位数的乘积的回文 - Palindrome from the product of two 3-digit numbers 使用 numpy 找到由两个 3 位数的乘积组成的最大回文 - Find the largest palindrome made from the product of two 3-digit numbers using numpy 查找由两个3位数组成的乘积所产生的最大回文 - Find the largest palindrome made from the product of two 3-digit numbers, just a small edit needed 欧拉计划:两个三位数数字的最大回文产品 - Project Euler: Largest palindrome product of two 3-digit number 最大回文集,是两个n位数字的乘积(Python) - Largest palindrome which is product of two n-digit numbers (Python) 在我的计算中,要从两个3位数的乘积中得到最大的回文数,在哪里出错? - where am I going going wrong in my calculations to get largest palindrome made from the product of two 3-digit numbers? 找出由两个 2 位数字的乘积构成的最大回文 - To find the largest palindrome made from the product of two 2-digit numbers 如何在python中找到由两个三位数组成的最大回文? - How to find the largest palindrome made of two three digit numbers in python? 从python中3个数字的乘积中找到最大的回文 - find the largest palindrome from the product of 3 numbers in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM