E
E
Eugene2018-08-26 10:37:40
Python
Eugene, 2018-08-26 10:37:40

How to simplify this python code?

Hello.
It was sad and lonely, so I wrote a rock-paper-scissors game. In the course of the solution, the following construction arose:

def whowin (first, second):
    if first == 'ножницы'   and second == 'камень':
        print("second win")
    elif first == 'камень'  and second == 'бумага':
        print('second win')
    elif first == 'бумага'  and second == 'ножницы':
        print('second win')

    elif first == 'ножницы' and second == 'бумага':
        print('first win')
    elif first == 'камень'  and second == 'ножницы':
        print('first win')
    elif first == 'бумага'  and second == 'камень':
        print("first win")

I can't help feeling that this solution is a crutch. Please advise how it can be rewritten more correctly.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
I
Ivan Sharapenkov, 2018-08-26
@sM0kfyz

1 - ножницы
2 - бумага
3 - камень

def whowin (first, second):
    result = (second - first) if abs(second - first) != 2 else -(second - first)
    if result == 0:
        print("ничья")
    elif result > 0:
        print('first win')
    else:
        print('second win')

Без ничьи
def whowin (first, second):
    result = (second - first) if abs(second - first) != 2 else -(second - first)
    print("first win" if result > 0 else "second win")

P
pcdesign, 2018-08-26
@pcdesign

def whowin(first, second):
    game = {('ножницы', 'камень'): "second win",
        ('камень', 'бумага'): 'second win',
        ('бумага', 'ножницы'): 'second win',
        ('ножницы', 'бумага'):  'first win',
        ('камень',  'ножницы'): 'first win',
        ('бумага'  'камень'): 'first win'}
    print(game[(first, second)])

Наверное, можно еще упростить.

D
Dimonchik, 2018-08-26
@dimonchik2013

def whowin (first, second):
    if any([
        all([first == 'ножницы',second == 'камень']),
        all([first == 'камень',second == 'бумага']),
        all([first == 'бумага',second == 'ножницы']),
        ]):
        return ('second win')
    elif any([
        all([first == 'ножницы',second == 'бумага']),
        all([first == 'камень',second == 'ножницы']),
        all([first == 'бумага',second == 'камень']),
        ]):
        return ('first win')
    else:
        return None

D
Dmitry, 2018-08-27
@cosmoskey

def whowin(first, second):
    rsp = ('rock', 'scissors', 'paper')
    if rsp.index(first) == rsp.index(second): # also can be first == second
        return 'draw'
    if (rsp.index(first) - rsp.index(second)) % 3 == 1:
        return 'second'
    else:
        return 'first'

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question