fork download
  1.  
  2. from itertools import permutations, compress
  3.  
  4. m = 3
  5. n = 3
  6.  
  7. def prettyPrint( single_division ):
  8. def clean(it):
  9. items = ", ".join(it)
  10. return "{" + items + "}"
  11.  
  12. def cleanIntSet(single_set):
  13. str_set = map(str, single_set)
  14. return clean( str_set )
  15.  
  16. sets = map( cleanIntSet, single_division )
  17. return clean(sets)
  18.  
  19. def candidates(n,m):
  20. def makeCandidate(perm):
  21. solution = []
  22. integers = range(1,n*m+1)
  23.  
  24. for setNumber in range(m):
  25. mask = map(lambda x: x == setNumber, perm)
  26. singleSet = compress(integers, mask)
  27. solution.append(frozenset(singleSet))
  28.  
  29. return frozenset(solution)
  30.  
  31. permutationBase = [i for j in range(n) for i in range(m)]
  32. allPermutations = set( permutations(permutationBase) )
  33.  
  34. return { makeCandidate(perm) for perm in allPermutations }
  35.  
  36. def isCorrectDivision(division):
  37. sums = map(sum, division)
  38. return len(set(sums)) == 1
  39.  
  40. answers = filter(isCorrectDivision,candidates(n,m))
  41. for answer in answers:
  42. print( prettyPrint(answer) )
  43.  
  44.  
Success #stdin #stdout 0.21s 5896KB
stdin
Standard input is empty
stdout
{{1, 5, 9}, {8, 3, 4}, {2, 6, 7}}
{{9, 2, 4}, {3, 5, 7}, {8, 1, 6}}