2016-08-27 107 views
-1
def has22(nums): 
    if nums[len(nums) - 1] == 2: 
    if nums[len(nums) - 2] == 2: 
     return True 
    else: 
    for n in range(len(nums) - 3): 
     if nums[n] == 2 : 
     if nums[n + 1] == 2: 
      return True 
     else: 
     return False 

我需要返回True,如果數組包含2旁邊的2某處。但它給了我一個錯誤:「列表索引超出範圍」。我應該改變什麼?CodingBat has22爲什麼這個解決方案是錯誤的?

我很新的東西,所以可能我的代碼是最長的解決方法之一,但我感謝任何幫助。謝謝!

+0

你能否粘貼整個錯誤? – Bharel

回答

1

我認爲只有nums是一個空列表時,您報告的錯誤纔會發生。在這種情況下,nums[len(nums) - 1]不是有效的索引(因爲沒有有效的索引進入空列表)。

對於這個問題,真的沒有太多的意思要特別封閉列表中的最後兩項。你可以讓你的代碼更通過處理所有的情況下用一個簡單的循環:

def has22(nums): 
    for n in range(len(nums) - 1): # the loop body will not run if len(nums) < 2 
     if nums[n] == nums[n + 1] == 2: # you can chain comparison operators 
      return True 
    return False # this is at top level (after the loop), not an `else` clause of the if 

正如評論說,在這裏我用列表索引循環體將無法運行,如果該列表的長度小於2這是因爲range將是空的,並且在空序列上迭代不會做任何事情。

稍微更有趣的方法是在兩個迭代器num上使用zip,它們被一個位置偏移。這是更高級的Python的東西,所以如果你不明白的是,不要過分擔心它:

def has22_fancy(nums): 
    iters = [iter(nums), iter(nums)] 
    next(iters[1], None) 
    return any(a == b == 2 for a, b in zip(*iters)) 

這種方法來遍歷使用zip對由itertools documentation,它給了啓發在pairwise食譜:

def pairwise(iterable): 
    "s -> (s0,s1), (s1,s2), (s2, s3), ..." 
    a, b = tee(iterable) 
    next(b, None) 
    return zip(a, b) 
相關問題