-1

I have a program, but it is not important.

from collections import Counter

def balance(left, right, result = 0):
    wages = {'!': 2, '?': 3}
    for key in Counter(left).keys():
        result += Counter(left).get(key) * wages.get(key)
    for key_ in Counter(right).keys():
        result -= Counter(right).get(key_) * wages.get(key_)
    if result == 0:
        return 'Balance'
    return 'Left' if result > 0 else 'Right'

Source for interesting: https://www.codewars.com/kata/57fb44a12b53146fe1000136

Is it possible to write this piece of code in one line?

if result == 0:
    return 'Balance'
return 'Left' if result > 0 else 'Right'
khelwood
  • 55,782
  • 14
  • 81
  • 108
Ashtart
  • 121
  • 5

1 Answers1

1

You can use Conditional expressions (sometimes called a "ternary operator"):

def balance(result: int) -> str:
    return 'Right' if result < 0 else 'Left' if result > 0 else 'Balance'

print(f'{balance(-1) = }')
print(f'{balance(0) = }')
print(f'{balance(1) = }')

Output:

balance(-1) = 'Right'
balance(0) = 'Balance'
balance(1) = 'Left'
Sash Sinha
  • 18,743
  • 3
  • 23
  • 40