From f81eefab01f71a43ce8fc2adde50d9138168eead Mon Sep 17 00:00:00 2001 From: RAJ Date: Sat, 18 Apr 2026 01:04:01 +0530 Subject: [PATCH] Refactor Rock Paper Scissor game logic Removing unnecessary positive and negative lists to execute the code in O(1) complexity --- rock_paper_scissor.py | 69 ++++++++++++++++++++----------------------- 1 file changed, 32 insertions(+), 37 deletions(-) diff --git a/rock_paper_scissor.py b/rock_paper_scissor.py index 1573f7e..065276f 100644 --- a/rock_paper_scissor.py +++ b/rock_paper_scissor.py @@ -1,46 +1,41 @@ import random -ROCK = 'rock' -PAPER = 'paper' -SCISSOR = 'scissor' -choices = [ROCK, PAPER, SCISSOR] -positive = [[PAPER, ROCK], [SCISSOR, PAPER], [ROCK, SCISSOR]] -negative = [[ROCK, PAPER], [PAPER, SCISSOR], [SCISSOR, ROCK]] +choices = ['rock', 'paper', 'scissor'] + +# What beats what +win_map = { + 'rock': 'scissor', + 'paper': 'rock', + 'scissor': 'paper' +} def get_computer_move(): return random.choice(choices) -def find_winner(user_move, computer_move): - if [user_move, computer_move] in positive: - return 1 - elif [user_move, computer_move] in negative: - return -1 - return 0 +def find_winner(user, comp): + if user == comp: + return "Tie" + elif win_map[user] == comp: + return "User Won" + else: + return "Computer Won" + +print("===== Rock Paper Scissor =====") -print("===== Welcome to Rock, Paper And Scissor Game =====") while True: - choice = input("Do you wanna play (y/n): ").strip().lower() - if choice == 'y': - computer_move = get_computer_move() - while True: - move = input("Select a move ('r' for rock/'p' for paper/'s' for scissor): ").strip().lower() - if move in ['r', 'p', 's']: - user_move = {'r': ROCK, 'p': PAPER, 's': SCISSOR}[move] - print(f"User Move: {user_move}") - print(f"Computer's Move: {computer_move}") - output = find_winner(user_move, computer_move) - if output == 1: - print("User Won !!!") - elif output == -1: - print("Computer Won !!!") - else: - print("It's a Tie !!!") - break - else: - print("Invalid input...please try again") - elif choice == 'n': - print("Exiting... Thanks for playing!") + if input("Play? (y/n): ").lower() != 'y': + print("Bye") break - else: - print("Invalid input...please try again") - print() + + move = input("r/p/s: ").lower() + + if move not in ['r', 'p', 's']: + print("Invalid input\n") + continue + + user_move = {'r': 'rock', 'p': 'paper', 's': 'scissor'}[move] + computer_move = get_computer_move() + + print("User:", user_move) + print("Computer:", computer_move) + print(find_winner(user_move, computer_move), "\n")