我是 python(和编程)新手,而且我陷入了 Project Euler 4。问题是:
“回文数的读法是一样的。两个 2 位数字的乘积构成的最大回文数是 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 结果呢?
我认为最简单的方法是使用字符串创建回文列表,但使用整数获取最大值。 这就是我想到的:
x = 100
pal = []
while 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
print(max(pal))
问题在于,在最后一个循环中,当您寻找最大值时,您比较的是字符串而不是整数。这样做,它会给你你期望的结果:
Largest = int(PalindromicNumber[0])
for p in PalindromicNumber:
if Largest <= int(p):
Largest = int(p)
根据 python 文档 字符串比较使用字典顺序:
比较使用字典顺序:首先比较前两项,如果它们不同,则确定比较的结果;如果它们相等,则比较接下来的两项,依此类推,直到耗尽任一序列。
//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)