[英]How to find the largest palindrome made of two three digit numbers in python?
I was trying Problem 4 on Project Euler when I ran into a problem. 当我遇到问题时,我正在Euler项目上尝试问题4。 Here is my code.
这是我的代码。
def Problem4():
x = 100
y = 909
a = []
b = []
x1 = []
y1 = []
while y < 1000:
while x < 1000:
z = x*y
if str(z) == str(z)[::-1]:
a.append(z)
x1.append(x)
y1.append(y)
else:
b.append(z)
x = x + 1
y = y + 1
print(a)
print(x1)
print(y1)
Problem4()
This code runs okay, but the value of y remains constant, even after the y = y + 1
. 该代码可以正常运行,但是y的值即使在
y = y + 1
之后也保持不变。 Why is it doing that? 为什么这样做呢? Is there a better way of doing this.
有没有更好的办法做到这一点。
I got the solution. 我找到了解决方案。 The reason why
y
didn't increase was because the value of x
didn't get reset from 1000
. y
没有增加的原因是因为x
的值没有从1000
重置。 It just automatically skipped that chunk of code because the value of x
was already 1000. This is my improved code which also sorts the array in order. 因为
x
的值已经是1000,所以它只是自动跳过了这段代码。这是我改进后的代码,它也对数组进行了排序。
def Problem4():
y = 100
a = []
x1 = []
y1 = []
while y < 1000:
y = y + 1
x = 100
while x < 1000:
z = x*y
if str(z) == str(z)[::-1]:
a.append(z)
x = x + 1
a.sort()
print(a)
Problem4()
move the x = 100
line to the position between first while loop and the second while loop would solve your problem. 将
x = 100
线移动到第一个while循环和第二个while循环之间的位置将解决您的问题。
def Problem4():
y = 909
a = []
b = []
x1 = []
y1 = []
while y < 1000:
x = 100
while x < 1000:
z = x*y
if str(z) == str(z)[::-1]:
a.append(z)
x1.append(x)
y1.append(y)
else:
b.append(z)
x = x + 1
y = y + 1
print(a)
print(x1)
print(y1)
Problem4()
As for "better", you might want to use xrange(): 至于“更好”,您可能要使用xrange():
a = []
for y in xrange(909, 1000):
for x in xrange(100, 1000):
x = x * y
if str(z) = str(z)[::-1]:
a.append(z)
a.sort()
print a
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.