Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def battle(atks, healths):
- def fight(foe: dict, ally: dict) -> bool:
- foe['health'] -= ally['atk']
- if foe['health'] > 0:
- ally['health'] -= foe['atk']
- return foe['health'] > 0
- warriors = [{"atk": atk, "health": health} for atk, health in zip(atks, healths)]
- foe = warriors[0]
- allies = sorted(warriors[1:], key=lambda a: a['atk'], reverse=True)
- allies_with_enough_health = [ally for ally in allies if ally['health'] > foe['atk']]
- allies_with_low_health = [ally for ally in allies if ally['health'] <= foe['atk']]
- while allies_with_enough_health:
- ally = allies_with_enough_health[0]
- foe_alive = fight(foe, ally)
- if not foe_alive:
- return len(allies_with_enough_health + allies_with_low_health)
- if ally['health'] <= foe['atk']: # if health enough just fight another round
- allies_with_enough_health.pop(0)
- allies_with_low_health += [ally]
- allies_with_low_health.sort(key=lambda a: a['atk'], reverse=True)
- while allies_with_low_health:
- ally = allies_with_low_health.pop(0)
- foe_alive = fight(foe, ally)
- if not foe_alive:
- return len(allies_with_low_health) + 1 # as we already popped this ally from the list
- return 0
- def test_battles():
- assert battle([1],
- [2]) == 0
- assert battle([1, 2],
- [2, 1]) == 1
- assert battle([2, 2],
- [2, 1]) == 1
- assert battle([2, 2],
- [3, 1]) == 0
- assert battle([2, 2, 1],
- [3, 1, 1]) == 1
- assert battle([2, 2, 3],
- [3, 1, 1]) == 2
- assert battle([3, 1, 2, 3, 4],
- [20, 4, 2, 4, 13]) == 4
- assert battle([3, 1, 2, 3, 4],
- [20, 4, 2, 4, 11]) == 4
- assert battle([3, 1, 2, 3, 4],
- [21, 4, 2, 4, 11]) == 3
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement