2017-02-13 131 views
0

當試圖用python來回答這個問題時,我遇到了一個問題,就是我創建的列表上的索引問題。問題是:Python:indexing - 歐拉項目8

1000位數字中十三個相鄰數字的最大乘積是多少?

這裏是我的程序:

# solves problem 8 hopefully 
def problem8(): 
    MAX = 0 
    maybeMAX =0 
    n = 73167176531330624919225119674426574742355349194934969835203127745063262395783180169848018694788518438858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450 
    lst = [] 
    while n != 0: ## This loop creates a list from the above number 
     n,d =divmod(n,10) 
     lst.append(d) #puts each value of the number onto the list as an integer 
    lst.reverse() 
    while (len(lst)> 12): 
     i = lst[0] 
     product = (lst[i]*lst[i+1]*lst[i+2]*lst[i+3]*lst[i+4]*lst[i+5]*lst[i+6]*lst[i+7]*lst[i+8]*lst[i+9]*lst[i+10]*lst[i+11]*lst[i+12]) 
     maybeMAX = product 
     if maybeMAX > MAX : 
      MAX =maybeMAX 
     lst.remove(lst[0]) 
    return MAX 
sol8 = problem8() 
print "The greatest product of thirteen adjacent digits is {}".format(sol8) 

這是我上面運行程序後收到錯誤:

============== RESTART: C:\Python27\04 Project Euler 5,6,7,8.py ============== 

Traceback (most recent call last): 
    File "C:\Python27\04 Project Euler 5,6,7,8.py", line 94, in <module> 
    sol8 = problem8() 
    File "C:\Python27\04 Project Euler 5,6,7,8.py", line 77, in problem8 
    product = (lst[i]*lst[i+1]*lst[i+2]*lst[i+3]*lst[i+4]*lst[i+5]*lst[i+6]*lst[i+7]*lst[i+8]*lst[i+9]*lst[i+10]*lst[i+11]*lst[i+12]) 
IndexError: list index out of range 
>>> 

我找不到任何回答了這個問題索引任何其他問題,所以任何幫助代碼將不勝感激。謝謝。

+1

'len(lst)> 12'不能確保'lst [i + 12]'是一個有效的索引。 –

+0

我不明白它應該如何工作。你基本上可以找到'lst [lst [0]] * lst [lst [0] +1] * ...',其中'lst [0]'是第一個數字。它沒有意義。 – Wolfram

+0

@Wolfram你說得對。其中,上面的代碼將名稱爲lst(i = lst [0])的列表中的第一個索引處的值與該索引處的值相乘,然後再乘以該索引處的值加上2,上。因此,在這種情況下,第一個點存儲在第一個點中的數字是7,然後在產品部分中,使用7作爲索引,並將存儲在那裏的值與8中存儲的值相乘等。 –

回答

0

我的問題是宣佈我等於lst [0],這使我等於該指數的值,因此在計算產品的部分,它不是通過lst並使用這些值,它只是增加了7這是在索引0

原值因此,我改變:

while (len(lst)> 12): 
    i = lst[0] 

到:

while (len(lst)> 13): 
    i = 0 

,並計算出正確的答案。