python 的欧拉计划 4:最大回文积

Project Euler 4 with python : Largest Palindrome Product

我是 python(和编程)的新手,而且我被困在 Project Euler 4 中。问题是:

"一个回文数读起来是一样的。两个两位数的乘积组成的最大回文数是9009 = 91 × 99。

找出由两个 3 位数的乘积构成的最大回文。

这是我到目前为止的结果:

ProductOfThree = []
ProductOfThreeSTR = []
PalindromicNumber = []
#This first for loop displays all the results possible from the product of two 3 digit Number
for k in range(100, 1000):
    for j in range(k, 1000):
        Result = k * j
        ProductOfThree.append(Result)
#This second loop converts the list of number to a list of string
for i in ProductOfThree:
    a = str(i)
    ProductOfThreeSTR.append(a)
#The third loop compare the digit of each number of the list to find all the palindromic number of that list
for d in ProductOfThreeSTR:
    if len(d) == 6:
        if (d[0] == d[5]) and (d[1] == d[4]) and (d[2] == d[3]):
            PalindromicNumber.append(d)
    elif len(d) == 5:
        if (d[0] == d[4]) and (d[1] == d[3]):
            PalindromicNumber.append(d)
#And finally here the program display the largest number of the list, which contains only the palindromic numbers
Largest = PalindromicNumber[0]
for p in PalindromicNumber:
    if Largest <= p:
        Largest = p        
print(Largest)

程序显示数字 99999 。重新阅读程序后,我发现带有 len(d) == 5 的 if 语句是无用的,因为我们要显示最大的数字,而 6 位数字总是大于 5 位数字.删除程序的这一部分后,我得到了我应该得到的结果 ( 906609 )。但我仍然想知道,即使我们试图找到 5 位数的回文数,通常当我们显示列表的最大数字时它们应该被忽略,那么为什么它给出 99999 结果?

问题是在你的最后一个循环中,当你寻找最大值时,你比较的是字符串而不是整数。这样做,它会给你你期望的结果:

Largest = int(PalindromicNumber[0])
for p in PalindromicNumber:
    if Largest <= int(p):
        Largest = int(p)   

根据 python docs 字符串比较使用字典顺序:

The comparison uses lexicographical ordering: first the first two items are compared, and if they differ this determines the outcome of the comparison; if they are equal, the next two items are compared, and so on, until either sequence is exhausted.

我认为最简单的方法是使用字符串创建回文列表,但使用整数获取最大值。这是我想出的:

x = 100

朋友=[]

当 x < 1000:

for i in range(100,1000):
    for j in range(100,1000):
        prod = str(i*j)
        if prod == prod[::-1]:
            pal.append(int(prod))
        x = x+1

打印(最大(pal))

//This would be more precise 
def largestpalin(n):
    lowerbound=0
    upperbound=0
    for i in range(1,n+1):
       upperbound=upperbound*10
       upperbound=upperbound+9
    lowebound=int(1+lowerbound/10)
    maxproduct=0
    for i in range(upperbound,lowerbound-1,-1):
        for j in range(i,lowebound-1,-1):
            product=i*j
            if product<maxproduct:
                 break
            num=product
            reverse=0
            while(num!=0):
               rem=num%10
               reverse=reverse*10+rem
               num=num//10
          if product==reverse and product>maxproduct:
               maxproduct=reverse
   return maxproduct
n=3
res=largestpalin(n)
print(res)