我对Python很新,并尝试了Project Euler的挑战。我目前无法让嵌套for循环正常工作。我的代码如下所示:
def palindrome():
for i in range(999,317,-1):
for a in range(999,317,-1):
s = str(i*a)
if s[0] == s[5] and s[1] == s[4] and s[2] == s[3]:
return(s)
print(palindrome())
该计划的目的是找到最大可能的回文,它是两个三位数的乘积。当我运行这个程序时,我一直得到答案580085.这是一个回文,但我知道这是错误的答案。
具体问题:
答案 0 :(得分:3)
试试这个:
def palindrome():
return max( i * j for i in range(999, 317, -1)
for j in range(i, 317, -1)
if str(i*j) == str(i*j)[::-1]
)
或更可读的方式:
def palindrome():
largest = 0
for i in range(999, 317, -1):
for j in range(i, 317, -1):
if str(i*j) == str(i*j)[::-1] and i*j > largest:
largest = i*j
return largest
答案 1 :(得分:2)
你非常接近。你的代码返回它找到的第一个回文,你想找到所有的回文,只返回最大的回文。尝试类似:
{
"id": "c1902c75-1550-43f6-9cc8-b0461f1dfac7",
"timestamp": "2016-12-22T19:58:13.49Z",
"result": {
"source": "agent",
"resolvedQuery": "echo test",
"action": "",
"actionIncomplete": false,
"parameters": {
"myInput": "test"
},
"contexts": [],
"metadata": {
"intentId": "062b4383-06a0-40fe-bbeb-9189db49aeb8",
"webhookUsed": false,
"webhookForSlotFillingUsed": "false",
"intentName": "Response"
},
"fulfillment": {
"speech": "",
"messages": [
{
"type": 0,
"speech": ""
}
]
},
"score": 0.75
},
"status": {
"code": 200,
"errorType": "success"
},
"sessionId": "70be8f65-81f0-40be-a271-84a2d4960224"
}
答案 2 :(得分:1)
目前你的代码终止于它找到的FIRST回文,例如它可能终止于999 * 400。然而,例如,可以在900 * 800处找到更大的回文(这些值不会,但你会得到这个想法)。
要解决此问题,您可以执行此操作:
def palindrome(x, y):
lis = [] # Contains the palindromes
for i in range(x,317,-1):
for a in range(y,317,-1):
s = str(i*a)
if s[0] == s[5] and s[1] == s[4] and s[2] == s[3]:
lis.append(i*a)
# Finding largest palindrome
largest = 0
for i in range(0, len(lis)):
if lis[i] > largest:
largest = lis[i]
return largest
print(palindrome(999, 999))
返回值:906609 不仅如此,您还可以修改此代码,以便为您提供所有可以找到的回文列表。
答案 3 :(得分:1)
这是您找到的第一个回文;它不是你能找到的最大的。循环工作如记录:首先,i = 999,你将从999 * 999下降到999 * 317。 然后你将回到外部循环,设置i = 998,并从a = 999开始。请注意,您的第一个独特产品998 * 998远远大于之前的两次迭代,即999 * 317。
解决这个问题的一种方法是保存到目前为止你找到的最大的回文,并且只有当你完成它们时才打印结果......或者当k * k <最大。
另一种方法是更改循环参数,以便从最大的产品开始工作。