Instead of writing bad code that works, I’ve been trying to write more readable code. However sometimes is it not necessary or doing ‘too much’? Additionally how do programmers read the problem and create an efficient solution without simply spamming for loops?
import string
def battle(my_army, opposing_army) -> str:
if len(my_army) != len(opposing_army):
return retreat(my_army, opposing_army)
win_count = 0
my_list = list(map(strength, my_army))
opposing_list = list(map(strength, opposing_army))
battle_result = list(map(lambda x, y: x-y, my_list, opposing_list))
win_count += sum((result > 0) - (result < 0) for result in battle_result)
if win_count > 0:
return "We won"
elif win_count < 0:
return "We lost"
else:
return "It was a tie"
def strength(char: str) -> int:
ALPHABET: str = "$" + string.ascii_letters
DIGITS: str = string.digits
if char in ALPHABET:
return ALPHABET.index(char)
elif char in DIGITS:
return DIGITS.index(char)
else:
return 0
def retreat(my_string: str, opposing_string: str) -> str:
len_my_string = len(my_string)
len_opposing_string = len(opposing_string)
if len_my_string > len_opposing_string:
return "Opponent retreated"
elif len_my_string < len_opposing_string:
return "We retreated"
print(battle("Hello", "World"))