fork download
  1. class Player(object):
  2. def __init__(self, deck):
  3. self.deck = deck
  4. self.battlefield = []
  5.  
  6. @property
  7. def alive(self):
  8. return bool(self.deck)
  9.  
  10. @property
  11. def last_played(self):
  12. return self.battlefield[-1][-1] if self.battlefield else None
  13.  
  14. def play(self, cards):
  15. self.battlefield.append(self.deck[:cards])
  16. del self.deck[:cards]
  17.  
  18. def battle(self, other):
  19. self.play(1)
  20. other.play(1)
  21.  
  22. def war(self, other):
  23. length = min(4, len(self.deck), len(other.deck))
  24. self.play(length)
  25. other.play(length)
  26.  
  27. def ties(self, other):
  28. return self.last_played == other.last_played
  29.  
  30. def beats(self, other):
  31. return self.last_played > other.last_played
  32.  
  33. def claim(self, other):
  34. while self.battlefield:
  35. self.deck.extend(self.battlefield.pop())
  36. self.deck.extend(other.battlefield.pop())
  37. assert self.battlefield == other.battlefield == []
  38.  
  39.  
  40. def _who_wins(deck_1, deck_2):
  41. p1, p2 = Player(deck_1), Player(deck_2)
  42. while p1.alive and p2.alive:
  43. if p1.last_played is None:
  44. p1.battle(p2)
  45. if p1.ties(p2):
  46. p1.war(p2)
  47. if not p1.ties(p2):
  48. winner, loser = (p1, p2) if p1.beats(p2) else (p2, p1)
  49. winner.claim(loser)
  50. return 1 if p1.alive else 2 if p2.alive else 0
  51.  
  52.  
  53. def war(decks_text):
  54. decks = (map(int, line.split()) for line in decks_text.splitlines())
  55. return _who_wins(*decks)
  56.  
  57. # Testing
  58.  
  59. tests = (
  60. '''5 1 13 10 11 3 2 10 4 12 5 11 10 5 7 6 6 11 9 6 3 13 6 1 8 1
  61. 9 12 8 3 11 10 1 4 2 4 7 9 13 8 2 13 7 4 2 8 9 12 3 12 7 5''',
  62. '''3 11 6 12 2 13 5 7 10 3 10 4 12 11 1 13 12 2 1 7 10 6 12 5 8 1
  63. 9 10 7 9 5 2 6 1 11 11 7 9 3 4 8 3 4 8 8 4 6 9 13 2 13 5''',
  64. '''1 2 3 4 5 6 7 8 9 10 11 12 13 1 2 3 4 5 6 7 8 9 10 11 12 13
  65. 1 2 3 4 5 6 7 8 9 10 11 12 13 1 2 3 4 5 6 7 8 9 10 11 12 13''',
  66. )
  67.  
  68. for test in tests:
  69. print war(test)
Success #stdin #stdout 0s 23352KB
stdin
Standard input is empty
stdout
2
2
0