在学习Python的同时,我在Kaggle上做练习。
基本上,我的问题归结为两个int之间的>比较器不能像我想要的那样工作。
问题是要编写一个函数来比较两个BlackJack指针(字符串列表)
我首先写了一个函数,它给出了一只手的值
def hand_val(hand):
ace_count=0
for i in range(len(hand)) :
val_hand=hand
if ((hand[i] == 'J') | (hand[i] == 'Q') | (hand[i] == 'K')):
val_hand[i]=10
elif (hand[i] == 'A'):
val_hand[i]=11
ace_count+=1
else :
val_hand[i]=int(hand[i])
value=0
for i in val_hand :
value = value + i
for i in range(ace_count) :
if value>21 :
value=value-10
return value然后另一个比较两只不同的手
def blackjack_hand_greater_than(hand_1, hand_2):
if (hand_val(hand_1)>21):
return False
elif (hand_val(hand_2)>21):
return True
elif (hand_val(hand_1)>hand_val(hand_2)):
return True
else:
return False(我知道我应该以return ((hand_val(hand_1)<22) and ((hand_val(hand_1)>hand_val(hand_2))or(hand_val(hand_2)>21)))的身份执行此操作,但使用单独的条件更具可读性)
使用这两只特定的手,第二个函数不能按预期工作。我想我已经设法将问题追溯到第一个elif,这是我写的调试代码
hand_1=['3', '2', '6', '8']
hand_2=['8', 'A', '5']
print(hand_val(hand_1))
print(hand_val(hand_2))
print(type(hand_val(hand_1)))
print(type(hand_val(hand_2)))
print(hand_val(hand_1)>21)
print(hand_val(hand_2)>21) ############# WHY??? OH WHY??
print(14>21)
print(hand_val(hand_1)>hand_val(hand_2))下面是输出
19
14
<class 'int'>
<class 'int'>
False
True
False
False看看print(hand_val(hand_2)>21)返回True,而print(14>21)应该返回False?
有人能帮帮忙吗?
发布于 2020-07-15 03:10:19
正确的写法:
def blackjack_hand_greater_than(hand_1, hand_2):
return and_val(hand_1) < 22 and (hand_val(hand_1) > hand_val(hand_2) or hand_val(hand_2) > 21)分成多行是:
def blackjack_hand_greater_than(hand_1, hand_2):
if and_val(hand_1) < 22:
if hand_val(hand_1) > hand_val(hand_2):
return True
elif hand_val(hand_2) > 21:
return True
else:
return False
else:
return Falsehttps://stackoverflow.com/questions/62902222
复制相似问题