2014-11-20 71 views
0

我試圖做的項目歐拉問題8.這背後是我在做什麼的總體思路:爲什麼我的列表越來越短?

  • 我節省了他們在一個文本文件給數字;
  • 我正在讀取文件中的數字到列表中;
  • 我正在檢查每行13個數字塊的產品;和
  • 現在我輸出哪組13號正在彌補塊(我這樣做是因爲我的輸出不斷涌現出錯誤,所以我要確保我的程序正確讀取每個數據塊。)

我有幾個問題出現在我的程序和我的故障排除過程中,我發現,出於某種原因,我的列表存儲當前行正在縮短,直到它不存在。我不知道爲什麼會發生這種情況,我該怎麼做才能解決這個問題?

這裏是我的源代碼:

with open("product.txt") as f: 
    array = [] 
    for line in f: 
     line = line.split() 
     if line: 
      line = [int(i) for i in line] 
      array.append(line) 

def product(k): #Largest product of row k 
    i = 0 #The start of the chunk of 13 terms 
    row = str(array[k][0]) 
    while i < len(row) - 12: #Stop when i is 13 characters away from end of row 
     j=0 #The start of our run-through of the chunk 
     total = 1 #Set this value to 1 so that we can compare the next chunk of 13 
     while j < 13: #Go outward to the 12th element only since we include 0 
      total = total * int(row[i+j]) #The first character * the next 12 
      j += 1 
      #End of j while 

     print (row[i:13]) #To verify that the program is reading size 13 blocks 
     i += 1 #End of i while 

    return total 

print (product(0)) 

的文本文件只是一個從problem 8數量的複製和粘貼。

回答

6

您的列表不會縮短任何位置,您只需要印刷越來越小。

您使用的是固定終點爲您的切片:

print (row[i:13]) 

你想使相對的是終點到起點:

print(row[i:i + 13]) 
+0

謝謝您澄清!當我讀到這些信息時,就像我說的那樣,我沒有經歷過編程,特別是在Python中 - 我只是幾乎沒有開始接受它。 – Seraphim 2014-11-20 18:48:26

0

歐拉問題是非常適合學習的基礎知識許多計算機語言,尤其是Python。歐拉8可以是單行代碼,如下所示:

print max([reduce(lambda x,y: x*y,map(int,input_string[i:i+13])) for i in xrange(len(input_string)-13)])