Advertisement
Guest User

Battle

a guest
Jan 25th, 2020
173
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.90 KB | None | 0 0
  1. def battle(atks, healths):
  2.     def fight(foe: dict, ally: dict) -> bool:
  3.         foe['health'] -= ally['atk']
  4.         if foe['health'] > 0:
  5.             ally['health'] -= foe['atk']
  6.         return foe['health'] > 0
  7.  
  8.     warriors = [{"atk": atk, "health": health} for atk, health in zip(atks, healths)]
  9.     foe = warriors[0]
  10.     allies = sorted(warriors[1:], key=lambda a: a['atk'], reverse=True)
  11.     allies_with_enough_health = [ally for ally in allies if ally['health'] > foe['atk']]
  12.     allies_with_low_health = [ally for ally in allies if ally['health'] <= foe['atk']]
  13.  
  14.     while allies_with_enough_health:
  15.         ally = allies_with_enough_health[0]
  16.         foe_alive = fight(foe, ally)
  17.         if not foe_alive:
  18.             return len(allies_with_enough_health + allies_with_low_health)
  19.         if ally['health'] <= foe['atk']:  # if health enough just fight another round
  20.             allies_with_enough_health.pop(0)
  21.             allies_with_low_health += [ally]
  22.  
  23.     allies_with_low_health.sort(key=lambda a: a['atk'], reverse=True)
  24.     while allies_with_low_health:
  25.         ally = allies_with_low_health.pop(0)
  26.         foe_alive = fight(foe, ally)
  27.         if not foe_alive:
  28.             return len(allies_with_low_health) + 1  # as we already popped this ally from the list
  29.  
  30.     return 0
  31.  
  32.  
  33. def test_battles():
  34.     assert battle([1],
  35.                   [2]) == 0
  36.     assert battle([1, 2],
  37.                   [2, 1]) == 1
  38.     assert battle([2, 2],
  39.                   [2, 1]) == 1
  40.     assert battle([2, 2],
  41.                   [3, 1]) == 0
  42.     assert battle([2, 2, 1],
  43.                   [3, 1, 1]) == 1
  44.     assert battle([2, 2, 3],
  45.                   [3, 1, 1]) == 2
  46.     assert battle([3, 1, 2, 3, 4],
  47.                   [20, 4, 2, 4, 13]) == 4
  48.     assert battle([3, 1, 2, 3, 4],
  49.                   [20, 4, 2, 4, 11]) == 4
  50.     assert battle([3, 1, 2, 3, 4],
  51.                   [21, 4, 2, 4, 11]) == 3
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement