![](/img/trans.png)
[英]Python : How to find in set of rows, one element is less than 1 and other is greater than 1?
[英]How to set that one variable is greater then the other in Python?
我正在尝试用Python创建一个“摇滚,纸张,剪刀”游戏,我想将一个变量设置为大于另一个变量。
就像是:
paper > rock
scissors > paper
rock > scissors
我怎么能这样做..?
是的,丹尼尔说,通过覆盖__cmp__
你可以实现这一点:
class Comparable(object):
def __init__(self, below_class, above_class):
self.above_class = above_class
self.below_class = below_class
def __cmp__(self, other):
if isinstance(other, self.below_class):
return 1
if isinstance(other, self.above_class):
return -1
return 0
class Paper(Comparable):
pass
class Rock(Comparable):
pass
class Scissors(Comparable):
pass
scissors = Scissors(Paper, Rock)
paper = Paper(Rock, Scissors)
rock = Rock(Scissors, Paper)
# True
print paper > rock
print scissors > paper
print rock > scissors
# False
print paper < rock
print scissors < paper
print rock < scissors
有关其工作方式的文档,请访问: https : //docs.python.org/2.6/reference/datamodel.html#object。 CMP
这实际上是一个有趣的问题,因为它提出了一些有用的想法。
例如,如果纸质剪刀遵循数学不平等的规律,那将是一个微不足道的问题。 让我们说paper > rock > scissors
在数学上是正确的(即paper > scissors
,与游戏规则相反):
class fist(object):
def __init__(self, weapon):
WEAPON_VALUES = {'paper': 2, 'rock': 1, 'scissors': 0}
self.weapon_value = WEAPON_VALUES[weapon]
def __gt__(self, other):
return self.weapon_value > other.weapon_value
def __lt__(self, other):
return self.weapon_value < other.weapon_value
def __eq__(self, other):
return self.weapon_value == other.weapon_value
def __ne__(self, other):
return self.weapon_value != other.weapon_value
paper = fist('paper')
rock = fist('rock')
scissors = fist('scissors')
现在我们可以查看:
In [7]: paper > rock
Out[7]: True
In [8]: rock == rock
Out[8]: True
In [9]: paper < scissors
Out[9]: False
In [10]: scissors < rock
Out[10]: True
不幸的是,纸质剪刀具有循环逻辑,因此通常的不平等概念在这种情况下不起作用(因此paper < scissors
评估为False
)。
您可以使用另一个答案中解释的自定义可比对象,但请记住,这会引起悖论,如rock > scissors > paper == True
当然当然是rock < paper
。
在你的情况下,我建议创建一个能够让胜利者回归的功能。 就像是
def winner(J1, J2):
if J1 == 'rock':
if J2 == 'paper':
return('J2')
if J2 == 'rock':
return('draw')
if J2 == 'paper':
return('J1')
...
这样可以让你看到谁赢了。
您可以通过在对象上定义__gt__
方法来覆盖>
运算符的行为。 有关更多信息,请参阅有关Python数据模型的文档 。
对于不涉及重新定义运算符的简单解决方案:
首先定义游戏规则:
rules = ['paper>rock', 'rock>scissors', 'scissors>paper']
并使用这样的函数来检查规则的数据:
def greater(opt1, opt2):
if opt1 == opt2:
return None # draw
return "{0}>{1}".format(opt1, opt2) in rules
>>> greater('paper','rock')
True
>>> greater('paper','scissors')
False
>>> greater('rock','paper')
False
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.