Playing the Alphabet War in Python

The challenge


There is a war and nobody knows – the alphabet war!
There are two groups of hostile letters. The tension between left side letters and right side letters was too high and the war began.


Write a function that accepts fight string consists of only small letters and return who wins the fight. When the left side wins return Left side wins!, when the right side wins return Right side wins!, in other case return Let's fight again!.

The left side letters and their power:

w - 4 p - 3 b - 2 s - 1

The right side letters and their power:

m - 4 q - 3 d - 2 z - 1

The other letters don’t have power and are only victims.


AlphabetWar("z"); //=> Right side wins! AlphabetWar("zdqmwpbs"); //=> Let's fight again! AlphabetWar("zzzzs"); //=> Right side wins! AlphabetWar("wwwwwwz"); //=> Left side wins!
Code language: JavaScript (javascript)

The solution in Python code

Option 1:

def alphabet_war(fight): left = { 'w': 4, 'p': 3, 'b': 2, 's': 1 } right = { 'm': 4, 'q': 3, 'd': 2, 'z': 1 } score = 0 for i in list(fight): if i in left: score -= left[i] elif i in right: score += right[i] if score > 0: return "Right side wins!" elif score < 0: return "Left side wins!" else: return "Let's fight again!"
Code language: Python (python)

Option 2:

def alphabet_war(fight): d = {'w':4,'p':3,'b':2,'s':1, 'm':-4,'q':-3,'d':-2,'z':-1} r = sum(d[c] for c in fight if c in d) return {r==0:"Let's fight again!", r>0:"Left side wins!", r<0:"Right side wins!" }[True]
Code language: Python (python)

Option 3:

def alphabet_war(fight): a, b = 'sbpw', 'zdqm' l, r = sum([a.find(x)+1 for x in fight]), sum([b.find(y)+1 for y in fight]) return "Right side wins!" if l<r else "Left side wins!" if r<l else "Let's fight again!"
Code language: Python (python)

Test cases to validate our solution

import test from solution import alphabet_war @test.describe("Fixed Tests") def fixed_tests():'Basic Test Cases') def basic_test_cases(): test.assert_equals(alphabet_war("z"), "Right side wins!") test.assert_equals(alphabet_war("zdqmwpbs"), "Let's fight again!") test.assert_equals(alphabet_war("wq"), "Left side wins!") test.assert_equals(alphabet_war("zzzzs"), "Right side wins!") test.assert_equals(alphabet_war("wwwwww"), "Left side wins!")
Code language: Python (python)
Notify of
Inline Feedbacks
View all comments