[英]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 結果呢?
我認為最簡單的方法是使用字符串創建回文列表,但使用整數獲取最大值。 這就是我想出的:
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
打印(最大(朋友))
問題在於,在最后一個循環中,當您尋找最大值時,您比較的是字符串而不是整數。 這樣做,它會給你你期望的結果:
Largest = int(PalindromicNumber[0])
for p in PalindromicNumber:
if Largest <= int(p):
Largest = int(p)
根據python docs字符串比較使用字典順序:
比較使用字典順序:首先比較前兩項,如果它們不同,則決定比較的結果; 如果它們相等,則比較接下來的兩個項目,依此類推,直到用完任一序列。
//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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.