首页 > 解决方案 > 有没有办法简化这个while条件(python)

问题描述

我一直在寻找一种方法来简化这个

while bluePoints < BOn // 2 + 1 and redPoints < BOn // 2 + 1:

我知道如何使用字符串和列表进行简化,但不知道如何使用整数

标签: pythonwhile-loopconditional-statements

解决方案


您应该澄清“一种简化此 while 条件的方法”的含义。这可以通过多种方式进行解释,您正在寻找的答案可能取决于其余代码中发生的情况。话虽如此,这里有一些替代条件应该导致相同的布尔值:

def bon_calc(bon : int) -> int:
    return bon // 2 + 1

def red_blu_check(red_p : int, blu_p : int, bon : int) -> bool:
    return blu_p < bon // 2 + 1 and red_p < bon // 2 + 1

bluePoints = 1
redPoints = 1
BOn = 2

# Your orignal function
con1 = bluePoints < BOn // 2 + 1 and redPoints < BOn // 2 + 1

# Using all instead of and
con2 = all([bluePoints < BOn // 2 + 1, redPoints < BOn // 2 + 1])

# Using custom function bon_calc
con3 = bluePoints < bon_calc(BOn) and redPoints < bon_calc(BOn)

# Using custom function red_blu_check
con4 = red_blu_check(redPoints, bluePoints, BOn)

assert con1 == con2 == con3 == con4

python 导师中的示例


推荐阅读