fork download
  1. import itertools
  2.  
  3. #for each item in `seq`, if it equals `value`, replace it with 0.
  4. def blank_all(seq, value):
  5. return [0 if item == value else item for item in seq]
  6.  
  7. #yields successive sequences such that each sequence has every instance of `value` replaced with zero except for a single instance.
  8. #ex. `blank_all_but_one([1,1,2,1], 1)` yields [1,0,2,0], [0,1,2,0], and [0,0,2,1].
  9. def blank_all_but_one(seq, value):
  10. for idx, item in enumerate(seq):
  11. if item == value:
  12. blanked = blank_all(seq, value)
  13. blanked[idx] = value
  14. yield blanked
  15.  
  16. #given a sequence that contains at least one `1` and `-1`, finds all possbile blankings of the sequence that contain at least one `1` and `-1`.
  17. def iter_pairs(seq):
  18. for a in blank_all_but_one(seq, 1):
  19. for b in blank_all_but_one(a, -1):
  20. yield b
  21.  
  22. #flips a matrix so that its rows becomes its columns, and vice versa.
  23. def transposed(matrix):
  24. return map(list, zip(*matrix))
  25.  
  26. #finds the cartesian product of a generator expression applied to each row of a matrix.
  27. def apply_to_each_row(matrix, func):
  28. for result in itertools.product(*[list(func(row)) for row in matrix]):
  29. yield list(result)
  30.  
  31. #same as `apply_to_each_row`, but done in column order instead
  32. def apply_to_each_column(matrix, func):
  33. for result in apply_to_each_row(transposed(matrix), func):
  34. yield transposed(result)
  35.  
  36. matrix = [[1,1,-1],
  37. [1,-1,-1],
  38. [-1,0,1]]
  39.  
  40. for result in apply_to_each_column(matrix, iter_pairs):
  41. print result
Success #stdin #stdout 0.01s 7736KB
stdin
Standard input is empty
stdout
[[1, 1, -1], [0, -1, 0], [-1, 0, 1]]
[[1, 1, 0], [0, -1, -1], [-1, 0, 1]]
[[0, 1, -1], [1, -1, 0], [-1, 0, 1]]
[[0, 1, 0], [1, -1, -1], [-1, 0, 1]]