2014-05-06 37 views
-1
def tableCheck(elev, n, m): 
    tablePosCount = 0 
    rowPosCount = 0 

    for r in range(1, n): 
     for c in range(1, m): 
     if elev[r][c] > 0:  
      tablePosCount = tablePosCount + 1 
      rowPosCount = rowPosCount + 1 
      print 'Number of positive entries in row ', r , ' : ', rowPosCount 
    print 'Number of positive entries in table :', tablePosCount 
    return tablePosCount 
elev = [[1,0,-1,-3,2], [0,0,1,-4,-1], [-2,2,8,1,1]] 
tableCheck(elev, 3, 5) 

我在讓代碼正常運行時遇到了一些困難。如果有人能告訴我,爲什麼它可能是給我這個輸出Python tablecheck error

Number of positive entries in row 1 : 1 
Number of positive entries in row 2 : 2 
Number of positive entries in row 2 : 3 
Number of positive entries in row 2 : 4 
Number of positive entries in row 2 : 5 
Number of positive entries in table : 5 

回答

0

有在你的代碼三件事情,我懷疑是錯誤的,但因爲你沒有描述你所期望的行爲,它可能是一個或其中更多是按預期工作的。

第一個問題是,每當您看到一個大於0的新值時,您都會打印出「行」數字。您可能想要將print 'Number of positive entries in row '行縮進兩級(甚至可以使用內部for循環)。

第二個問題是,您不會重置每行的計數,因此我建議您移動的打印語句不會在第一行之後提供正確的輸出。您可能需要將rowPosCount = 0行移入外部循環。

最後一個問題是,你跳過第一行和每個後面的行的第一個值。這是因爲您的range1變爲nm。 Python索引從0開始,範圍排除它們的上限。你可能想要for r in range(n)for c in range(m),儘管迭代表值本身(或枚舉它們)會更加Pythonic。