5

I have the following code:

scores = [matrix[i][i] / sum(matrix[i]) for (i, scores) in enumerate(matrix)]

My problem is that sum(matrix[i]) could be 0 in some cases, resulting in a ZeroDivisionError. But because matrix[i][i] is also 0 in that case, I solved this as follows:

scores = [divide(matrix[i][i], sum(matrix[i])) for (i, scores) in enumerate(matrix)]

The function divide(x, y) returns 1 if y == 0 and (x / y) if y > 0. But I wonder if there is an easier way. Maybe I could use some ternary operator, but does that exist in Python?

Georgy
  • 12,464
  • 7
  • 65
  • 73
Lewistrick
  • 2,649
  • 6
  • 31
  • 42

3 Answers3

6

Yes, in Python it's called the conditional expression:

[matrix[i][i] / sum(matrix[i]) if sum(matrix[i]) != 0 else 0 
 for (i, scores) in enumerate(matrix)]
Georgy
  • 12,464
  • 7
  • 65
  • 73
TerryA
  • 58,805
  • 11
  • 114
  • 143
2
[(lambda x, y: 0 if y == 0 else x/y)(row[i], sum(row))
 for i, row in enumerate(matrix)]
Georgy
  • 12,464
  • 7
  • 65
  • 73
falsetru
  • 357,413
  • 63
  • 732
  • 636
1

Ternary conditionals do exist:

'blah' if True else 'wee'
Georgy
  • 12,464
  • 7
  • 65
  • 73