2017-03-17 79 views
1

我打算寫一個函數,我可以用它來總結所有數字的有兩位數的列表。例如:我怎樣才能更好地寫這些功能纔有意義

a=[1,2,11,100,10] 

should return 21 since 11 and 10 of the list are having two digits 

我也想數的範圍爲(0,1,2,... 100000)

def solution(A): 
    for integer in A: 
     if integer > 9 and integer <100: 
      two_digits_array.append(integer) 
    return sum(two_digits_array) 

我想這是正常的,所以在測試:

Example test: numbers= [47, 1900, 1, 90, 45] 
print (solution(numbers)) 
wow it works perfectly and returns 182 

但我想這些:

q= [1, 1000, 80, -91] 
WRONG ANSWER (got 80 expected -11) 

我怎麼能去關於它,爲什麼失敗。

+0

貌似從-10到-99號也被認爲是有兩個數字。因此,在你的for循環中,你必須檢查:「如果整數> 9,整數<100或整數<-9和整數> -100」 – mkabanen

回答

1

您正在檢查大於9,數小於100。試試:

如果整數> 9和整數< 100或整數> -100和整數< -9:

+0

是正確的,但爲什麼要編寫一個函數,創建額外的開銷,而不是你可以使用內建 –

+0

@binayr在一行中產生的結果 - 它並不總是使用內置在方法和單線。如果問題作者在尋求作業幫助(看起來像什麼),那麼幫助修復它的代碼比僅僅提供沒有任何解釋的答案要好。我非常不喜歡Stackoverflow的答案,只是「繼承我的代碼,它只是工作,使用這個」。如果你幫助他改善,你真的幫助人。 – mkabanen

4

爲什麼這麼難?您可以簡單地使用帶有濾波器的發生器,並將該發生器傳遞給內建的sum(..)。像:

def solution(A): 
    return sum(x for x in A if -100 < x < -9 or 9 < x < 100)

或者爲@PawełKordowski表明,使用abs(..),使病情更加優雅:

def solution(A): 
    return sum(x for x in A if 9 < abs(x) < 100)

不需要聲明附加陣列(只會消耗內存)。

<expr> for <var> in <iterable> if <condition>發生器:它由如果<condition>滿足在<iterable><var>施加<expr>每元件產生懶惰地數字序列。

+2

你可以使用'abs'使常量更短 –

+0

@PawełKordowski:的確是一個好主意,更新。 –

+0

不知道這是如何比較'len(str(x))== 2',可能轉換爲str較慢但不確定,因爲鏈接... –

2

試試這個

print sum(filter(lambda x: (x<100 and x>9) or (x>-100 and x<-9), a)) 

假設是列表中。

+0

感謝......爲達到爲我的aid..it現在對我的作品與所有測試cases..am這麼多的感謝 – Udonse

+0

@Udonse歡​​迎您。 –

2

請使用更新後的腳本

def solution(A): 
    for integer in A: 
     if (integer > 9 and integer < 100) or (integer > -100 and integer < -9): 
      two_digits_array.append(integer) 
    return sum(two_digits_array) 
1

您可以使用LEN()計算無數字:

ans=0 
for i in a: 
    if(len(str(abs(i)))==2: 
     ans+=i 
return ans 
+1

但是'len(str(-10))'是3 ... –