Zac*_*ith 0 python for-loop xrange
出于某种原因,在第一x变量for...循环从改变int到str通过代码的单次迭代后.我很困惑为什么必须这样,但每次我运行这个脚本时,我的集合最终会被包含数百个零的字符串填充.
如果有人好奇,这是尝试解决欧拉的问题4.
# A palindromic number reads the same both ways.
# The largest palindrome made from the product
# of two 2-digit numbers is 9009 = 91 99.
# Find the largest palindrome made from the product of two 3-digit numbers.
def palindrome():
products = set()
for x in xrange(700,999):
for y in xrange(700,999):
temp = x*y
n = [x for x in str(temp)]
if temp not in products:
if len(n)%2 == 0:
half = len(n)/2
first = n[:half]
last = n[half:]
last.reverse()
if first == last:
products.add(temp)
return products
if __name__ == "__main__":
n = palindrome()
print n
Run Code Online (Sandbox Code Playgroud)
在python 2.x中,列表推导将其变量泄漏到封闭范围.所以你的列表理解会[x for x in str(temp)]覆盖x的值.但请注意,它将在外循环的下一次迭代中返回到int.
| 归档时间: |
|
| 查看次数: |
790 次 |
| 最近记录: |