简体   繁体   English

即使条件为假,如果 function 执行也会出现问题

[英]Issue with if function executing even if the condition is false

I have this question for a practice assignment:我有一个练习作业的问题:

In Cee-lo, having a roll where two of the three dice have the same value is called a point.在 Cee-lo 中,掷出三个骰子中的两个具有相同值的点数称为点数。 This is the second weakest dice roll, only stronger than a 1-2-3.这是第二弱的骰子,仅比 1-2-3 强。 Complete the is_point() function that takes a single string parameter dice_str consisting of three dice values.完成 is_point() function,它采用由三个骰子值组成的单个字符串参数 dice_str。 If the dice rolled (as represented by the dice_str) have two of the three dice with the same value, the function should return True.如果掷出的骰子(由 dice_str 表示)三个骰子中有两个具有相同的值,则 function 应返回 True。 Otherwise, the function should return False.否则,function 应该返回 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

In my code, I use the first if function to test whether the count number does not appear twice.在我的代码中,我使用第一个 if function 来测试计数是否没有出现两次。 However, it seems to always be executing.但是,它似乎总是在执行。 For example, if my number is 141, it will still execute the if function and add the count by one even though that is not what I want it to do.例如,如果我的号码是 141,它仍然会执行 if function 并将计数加一,即使这不是我想要的。 I have tried printing the index_zero and from_index1 values and they are indeed the same number.我尝试打印 index_zero 和 from_index1 值,它们确实是相同的数字。 So why is the if function not executing?那么为什么 if function 没有执行呢?

An easier strategy is to convert your string into a set which gets rid of duplicates.一个更简单的策略是将您的字符串转换为一个消除重复的集合。 If the length of the set is 2 (not 1 or 3), then you have exactly 2 identical numbers:如果集合的长度是 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM