fork download
  1. #!/usr/bin/python3
  2.  
  3. _cache = {}
  4. def sums(addends, sum):
  5. """Return list of tuples of @addends addends that sums up to @sum."""
  6. global _cache
  7. if addends < 1 or sum < addends:
  8. return []
  9. if (addends, sum) not in _cache:
  10. result = [] if addends > 1 else [(sum,)]
  11. for d in reversed(range(1, sum)):
  12. result.extend([(d,) + a for a in sums(addends-1, sum-d) if len(a) == 0 or d >= a[0]])
  13. _cache[addends, sum] = result
  14. return _cache[addends, sum]
  15.  
  16. def compare(dieA, dieB):
  17. """Return sum over all possible die game results.
  18. Die A wins: +1, die B wins -1, tie: 0."""
  19. return sum([1 if a > b else -1 for a in dieA for b in dieB if a != b])
  20.  
  21.  
  22.  
  23. def iterate():
  24. """Return the best die for me if opponent has die X with given probability (distribution[X]).
  25. Then update distribution to linear (0: worst die, max: best die (max chosen in such a way that probs add up to one))
  26. or uniformly choose k-best dice."""
  27. global dice, distribution, score
  28. score = {}
  29. for myDie in dice:
  30. score[myDie] = 0
  31. for otherDie in dice:
  32. score[myDie] += compare(myDie, otherDie) * distribution[otherDie]
  33. dice = sorted(dice, key=lambda die: score[die], reverse=True)
  34. #distribution = {die: 2*i/len(dice)**2 for i, die in enumerate(reversed(dice), 1)}
  35. best = 3
  36. distribution = {die: 1/best if die in dice[:best] else 0 for i, die in enumerate(reversed(dice), 1)}
  37.  
  38. def reportAll():
  39. global score, dice
  40. for die in dice:
  41. print("{}\t{}\t".format(die, score[die]), distribution[die])
  42.  
  43. # initialize to uniform distribution
  44. dice = sums(6, 27)
  45. distribution = {die: 1/len(dice) for die in dice}
  46. score = {die: 0 for die in dice}
  47.  
  48. # iterate and print best die
  49. for _ in range(20):
  50. die = dice[0]
  51. print("{}\t{}\t".format(die, score[die]), distribution[die])
  52. iterate()
Runtime error #stdin #stdout 4.99s 5956KB
stdin
Standard input is empty
stdout
Standard output is empty