如何找到python中两个三位数组成的最大回文数?
How to find the largest palindrome made of two three digit numbers in python?
当我 运行 遇到问题时,我正在尝试 Euler 项目的问题 4。这是我的代码。
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()
此代码运行正常,但 y 的值保持不变,即使在 y = y + 1
之后也是如此。为什么要这样做?有没有更好的方法来做到这一点。
我得到了解决方案。 y
没有增加的原因是 x
的值没有从 1000
重置。它只是自动跳过了那段代码,因为 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()
将 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()
至于 "better",您可能需要使用 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
当我 运行 遇到问题时,我正在尝试 Euler 项目的问题 4。这是我的代码。
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()
此代码运行正常,但 y 的值保持不变,即使在 y = y + 1
之后也是如此。为什么要这样做?有没有更好的方法来做到这一点。
我得到了解决方案。 y
没有增加的原因是 x
的值没有从 1000
重置。它只是自动跳过了那段代码,因为 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()
将 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()
至于 "better",您可能需要使用 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