首页 > 解决方案 > 即使条件为假,如果函数执行也会出现问题

问题描述

我有一个练习作业的问题:

在 Cee-lo 中,掷出三个骰子中的两个具有相同值的点数称为点数。这是第二弱的骰子,仅比 1-2-3 强。完成 is_point() 函数,该函数采用由三个骰子值组成的单个字符串参数 dice_str。如果掷出的骰子(由 dice_str 表示)三个骰子中有两个具有相同的值,则该函数应返回 True。否则,该函数应返回 False。

def is_point(dice_str):
dice_str = "0" + dice_str # 0123
count = 1
while count < 7:
    count = str(count)
    index_zero = dice_str.find(count, 0, 2)
    from_index1 = dice_str.find(count, 2, 3)
    print(dice_str[index_zero])
    print(dice_str[from_index1])
    
    if index_zero == -1 or from_index1 == -1:
        count = int(count) + 1
        print(count)
    else:
        if dice_str[index_zero] == dice_str[from_index1]:
            return True
return False

在我的代码中,我使用第一个 if 函数来测试计数是否没有出现两次。但是,它似乎总是在执行。例如,如果我的号码是 141,它仍然会执行 if 函数并将计数加一,即使这不是我想要的。我尝试打印 index_zero 和 from_index1 值,它们确实是相同的数字。那么为什么 if 函数没有执行呢?

标签: pythonpython-3.x

解决方案


一个更简单的策略是将您的字符串转换为一个消除重复的集合。如果集合的长度是 2(不是 1 或 3),那么您正好有 2 个相同的数字:

def is_point(dice_str):
    return len(set(dice_str)) == 2


print(is_point('122')) #True
print(is_point('136')) #False
print(is_point('666')) #False

推荐阅读