![](/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.