2016-03-04 37 views
0
def recListSum(lst): 
    '''Takes an arbitrarily nested list as a parameter and returns the sum of 
the numbers in the list''' 
    if len(lst)==0: 
     return 0 
    if len(lst) > 0: 
     val = recListSum(lst[1:])+recListSum(lst[0]) 
     if type(lst[0]) != list: 
      if type(lst[0])==float or type(lst[0])==int: 
       return val 
     if type(lst[0])==list and len(lst[0])>0: 
      val = recListSum(lst[1:])+recListSum(lst[0]) 
      return val 
+0

什麼是你的問題? :) – DaveBensonPhillips

+0

我不斷收到一個'int'類型的對象有沒有len()錯誤@ user3697163 – Val

+0

哪一行?您需要編輯問題以包含所有這些相關詳細信息。人們不會用梳子來找出錯誤。 – DaveBensonPhillips

回答

0

根據您的評論,這聽起來像是您給len()函數一個整數值。由於一個數字沒有真正的長度,這會引發錯誤。

我會檢查,「lst」實際上是一個列表,當你假設它是(可能調用此方法導致「lst」成爲一個整數之前的一些錯誤)。

我認爲你最後一條if語句的第一個條件是保護那裏的len()函數,但是如果我對「lst」有時只是一個整數有所懷疑,

0

這是一個可能的解決方案。

def recListSum(lst): 
    '''Takes an arbitrarily nested list as a parameter and returns the sum of 
the numbers in the list''' 
    # handle trivial cases 
    if len(lst) == 0: 
     return 0 
    if len(lst) == 1: 
     return lst[0] 

    # sum and unfold 
    total = 0 
    new_lst = [] 
    for item in lst: 
     if isinstance(item, list): 
      new_lst += item 
     else: 
      total += item 
    new_lst.append(total) 

    # recurse 
    return recListSum(new_lst) 
+0

這產生aTraceback(最近一次調用最後): 文件 「」,第1行,在 recFloatCount([[12],4,6]) 文件 「」,第10行,在recFloatCount VAL = recFloatCount (lst [1:])+ lst [0] TypeError:不支持的操作數類型爲+:'int'和'list' – Val

0

一個簡單的方法列在下面。 我認爲lstlist其中包括listintfloat

def recListSum(lst): 
    if type(lst) in (int,float): 
     return lst 
    elif not type(lst) is list: 
     raise TypeError 
    elif len(lst) == 0: 
     return 0 
    else: 
     return recListSum(lst[0])+recListSum(lst[1:])