2012-08-08 60 views
0

由於某種原因,第一個循環中的x變量從代碼int變爲str。我很困惑,爲什麼必須這樣做,但每次運行這個腳本時,我的設置最終都會被包含數百個零的字符串填充。xrange生成字符串?我不明白

如果有人想了解,這是解決歐拉的問題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 
+1

聽起來像功課。 – 2012-08-08 07:53:08

+0

@InbarRose:OP說他在做[歐拉項目的問題#4](http://projecteuler.net/problem=4) – Kimvais 2012-08-08 08:09:36

回答

3

因爲 assing一個字符串,它會變成一個字符串的嘗試:

 n = [x for x in str(temp)] 

誤區像這些是你應該避免使用一個字母變量的原因。也就是說,我通常使用_作爲列表解析中的一次性變量...

7

在python 2.x中,列表解析會將其變量泄漏到封閉範圍中。所以你的列表理解[x for x in str(temp)]會覆蓋x的值。但請注意,它將在外循環的下一次迭代中返回到int。

3

不要在以下列表中使用x理解n = [x for x in str(temp)]。只需選擇另一個變量名稱即可。

-1
1 for x in xrange(700,999): 
2  for y in xrange(700,999): 
3   temp = x*y 
4   n = [x for x in str(temp)] 

後步驟#4中,n = [ '4', '9', '0', '0', '0', '0']中,x = '0'

然後對於下一步#3,temp ='0'* 701