首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python中“>”的奇怪错误

Python中“>”的奇怪错误
EN

Stack Overflow用户
提问于 2020-07-15 03:02:24
回答 1查看 80关注 0票数 0

在学习Python的同时,我在Kaggle上做练习。

基本上,我的问题归结为两个int之间的>比较器不能像我想要的那样工作。

问题是要编写一个函数来比较两个BlackJack指针(字符串列表)

我首先写了一个函数,它给出了一只手的值

代码语言:javascript
复制
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

然后另一个比较两只不同的手

代码语言:javascript
复制
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,这是我写的调试代码

代码语言:javascript
复制
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))

下面是输出

代码语言:javascript
复制
19
14
<class 'int'>
<class 'int'>
False
True
False
False

看看print(hand_val(hand_2)>21)返回True,而print(14>21)应该返回False

有人能帮帮忙吗?

EN

回答 1

Stack Overflow用户

发布于 2020-07-15 03:10:19

正确的写法:

代码语言:javascript
复制
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)

分成多行是:

代码语言:javascript
复制
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 False
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62902222

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档