2015-10-04 35 views
1
def sum_evens_2d(xss): 
    i = 0 
    counter = 0 
    while (i < len(xss)): 
     if(xss[i]%2 == 0): 
      counter += xss[i] 
      i= i+1 
     else: 
      i = i+1 
    return(counter) 

我試圖找到在列表中的平均值的總和。我的限制是我不能使用sum()。當我使用這個時,我得到一個TypeError。 我不想用循環,但我想我也有。所以,請解釋爲什麼我也會得到TypeError,以便我不會在將來嘗試這樣做。如何在Python中使用遞歸在列表中找到偶數的和?

回答

1

提供的代碼正常工作。 因此嘗試使用sum爲discribed如下:

xss = range(5) 
print sum(el for el in xss if el % 2 == 0) 
+0

我不能使用sum() –

+0

你說你不能使用'sum()',因爲你得到一個錯誤。所以有一個正確的方法如何使用'sum()'。 –

+0

不,我不能使用它,因爲我被限制不使用它的教授。 –

0

如果你不能使用sum並且必須有遞歸,你可以這樣做:

def s(xss): 
    if not xss: 
     return 0 # for when the list is empty 
    counter = 0 if xss[0] % 2 != 0 else xss[0] 
    return counter + s(xss[1:]) 
+0

對於%:'list'和'int',不確定的操作數類型我仍然得到TypeError –

+0

您的列表包含哪些類型的元素?這是全部'int'嗎? – DorElias

+0

它只包含整數 –

0

剛剛測試這一個,它應該工作:

def even_sum(a): 
    if not a: 
     return 0 
    n = 0 
    if a[n] % 2 == 0: 
     return even_sum(a[1:]) + a[n] 
    else: 
     return even_sum(a[1:]) 

# will output 154 
print even_sum([1, 2, 3, 4, 5, 6, 7, 8, 23, 55, 45, 66, 68]) 
+0

'even_sum(range(10000))' –

相關問題