gpt4 book ai didi

Python - "rock paper scissors"逻辑条件的简化

转载 作者:太空宇宙 更新时间:2023-11-04 07:28:37 27 4
gpt4 key购买 nike

我正在解决一个问题,它说:

In Big Bang Theory, Sheldon and Raj created a new game: "rock-paper-scissors-lizard-Spock".

The rules of the game are:

  • scissors cuts paper;
  • paper covers rock;
  • rock crushes lizard;
  • lizard poisons Spock;
  • Spock smashes scissors;
  • scissors decapitates lizard;
  • lizard eats paper;
  • paper disproves Spock;
  • Spock vaporizes rock;
  • rock crushes scissors.

In the case of Sheldon's victory, he would've said: "Bazinga!"; if Raj had won, Sheldon would declare: "Raj cheated"; in ties, he would request a new game: "Again!". Given the options chosen by both, make a program that prints Sheldon reaction to the outcome.

The input consists of a series of test cases. The first line contains a positive integer T (T ≤ 100), which represents the number of test cases. Each test case is represented by a line of the input, containing the choices of Sheldon and Raj, respectively, separated by a space.

我这道题的代码是

T = int(input())

for i in range(T):
Sheldon, Raj = input().split(' ')

if(Sheldon == "scissors" and (Raj == "paper" or Raj == "lizard")):
Win = True
elif(Sheldon == "lizard" and (Raj == "paper" or Raj == "Spock")):
Win = True
elif(Sheldon == "Spock" and (Raj == "rock" or Raj == "scissors")):
Win = True
elif(Sheldon == "paper" and (Raj == "rock" or Raj == "Spock")):
Win = True
elif(Sheldon == "rock" and (Raj == "scissors" or Raj == "lizard")):
Win = True
elif(Raj == "scissors" and (Sheldon == "paper" or Sheldon == "lizard")):
Lose = True
elif(Raj == "lizard" and (Sheldon == "paper" or Sheldon == "Spock")):
Lose = True
elif(Raj == "Spock" and (Sheldon == "rock" or Sheldon == "scissors")):
Lose = True
elif(Raj == "paper" and (Sheldon == "rock" or Sheldon == "Spock")):
Lose = True
elif(Raj == "rock" and (Sheldon == "scissors" or Sheldon == "lizard")):
Lose = True
elif(Sheldon == Raj):
Tie = True

if(Win == True):
print("Case #{0}: Bazinga!".format(i+1))
elif(Lose == True):
print("Case #{0}: Raj cheated!".format(i+1))
elif(Tie == True):
print("Case #{0}: Again!".format(i+1))

Win = Lose = Tie = False

但我觉得它太长了。有什么办法可以减少吗?

最佳答案

首先,恭喜你尝试写这篇文章!对于第一次尝试,您的逻辑非常好。

下一步是制作一个数据结构,您可以用相同的方式查询规则。 字典 比较合适:

options = {
'scissors': ('paper', 'lizard'),
'paper': ('rock', 'spock'),
'rock': ('lizard', 'scissors'),
'lizard': ('spock', 'paper'),
'spock': ('scissors', 'rock'),
}

然后你可以查询它而不是重复大量的 ifs:

if raj == sheldon:
print("Case #{0}: Again!".format(i+1))
elif raj in options[sheldon]:
print("Case #{0}: Bazinga!".format(i+1))
else:
print("Case #{0}: Raj cheated!".format(i+1))

关于Python - "rock paper scissors"逻辑条件的简化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52600712/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com