2017-09-06 3 views
0

ゼロ要素以下の要素をゼロで置き換え、行列の残りの要素の合計を出力する方法を解決する必要があります。マトリックスパズルの特定の要素を変更する - Python

たとえば、[[0,3,5]、[3,4,0]、[1,2,3]]は3 + 5 + 4 + 1 + 2の合計を出力する必要があります。 。

これまでのところ:

def matrixElementsSum(matrix): 
    out = 0 
    # locate the zeros' positions in array & replace element below 
    for i,j in enumerate(matrix): 
     for k,l in enumerate(j): 
       if l == 0: 
       break 
      out += l 
    return out 

コード出力一見ランダムな数字。 誰かが間違っていることを修正できますか?ありがとう

答えて

1

ゼロ要素の下にある要素を簡単に削除するには、the zip functionを使用します。

def matrixElementsSum(matrix): 
    out = 0 
    # locate the zeros' positions in array & replace element below 
    for i,j in enumerate(matrix): 
     # elements in the first row cannot be below a '0' 
     if i == 0: 
      out += sum(j) 
     else: 
      k = matrix[i-1] 
      for x, y in zip(j, k): 
       if y != 0: 
        out += x 
    return out 

ここで変数を少し意味のある名前を付けることを検討してください。あなたは、コードがさらに読みやすくするためにlist comprehensionsになっているはずです

def matrixElementsSum(matrix): 
    out = 0 
    # locate the zeros' positions in array & replace element below 
    for row_number, row in enumerate(matrix): 
     # elements in the first row cannot be below a '0' 
     if row_number == 0: 
      out += sum(row) 
     else: 
      row_above = matrix[row_number - 1] 
      for element, element_above in zip(row, row_above): 
       if element_above != 0: 
        out += element 
    return out 

:ような何か。

+0

ありがとう、私が頼んだのはまさに、ポインタのおかげです。さらに、下の行をすべてブロックするにはどうしますか? – Tarae

関連する問題