【问题标题】:Largest palindrome product of three digits三位数的最大回文乘积
【发布时间】:2014-01-31 07:55:35
【问题描述】:
我从 Project Euler 中为这个问题在 python 中编写了以下代码:Largest palindrome product
y = 1000
x = 1000
while y >= 100:
y-=1
while x >= 100:
x-=1
product = y*x
string = str(product)
if str(product) == string[::-1]:
print(product)
但这并没有在空闲时输出任何东西......这是什么问题?
【问题讨论】:
标签:
python
string
while-loop
palindrome
【解决方案1】:
你需要在外循环内重新初始化x:
while y >= 100:
x = 1000
...
【解决方案2】:
您需要在循环中初始化 x。但是使用 for 循环要容易得多,并且完全避免了初始化问题。
for y in range(100, 1000):
for x in range(100, 1000):
prod = x * y
if str(prod) == str(prod)[::-1]:
print(prod)
【解决方案3】:
##对于初学者...这可能对你有帮助!! ##
pro=[]
fin=[]
my_num=[]
x=[]
rev_num=[]
for a in range (100,1000):
for b in range (100,1000):
my_num.append(str(a*b))
l1= len(my_num)
for i in range(0,l1):
rev_num.append(my_num[i][::-1])
for j in range(0,l1):
if(my_num[j]==rev_num[j]):
pro.append(int(my_num[j]))
pro.sort()
print(f'Largest palindrome product in the range is {pro[-1]}')