这个条件想要比较什么?

2024-09-25 08:38:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在学习python,遇到了这个函数。你知道吗

def min(root, min_t): # min_t is the initially the value of root
    if not root:
        return min_t

    if root.key < min_t:
        min_t = root.key

    min_t = min(root.left, min_t)
    min_t = min(root.right, min_t)

    return min_t

我很不明白“如果不是根”是什么意思。它试图给出什么条件?如果“根”不是什么?“如果”想要做什么比较?你知道吗

更新:根是一个具有子树的二叉树自左以及自我权利. 在中也可以是无。如果节点是叶节点,则会出现这种情况。你知道吗


Tags: ofthekey函数returnif节点is
3条回答

在Python中,if expr:实际上意味着if bool(expr):,即它计算给定给它的任何表达式,然后将结果转换为布尔值(当然,在许多情况下,它已经是一个布尔值,例如x > y将是TrueFalse*)。你知道吗

内置类型有rules for boolean evaluation;简而言之,空容器和序列(dictlisttuplesetstr等)加上零数值(00.00j等)和None求值False-y,任何其他类型都被认为是True-y。用户实现的类型通常遵循此约定。你知道吗

这使得if root成为方便的快捷方式,例如if root != 0if len(root) > 0,这取决于root对象的类型。请注意,None通常根据the style guide使用if name is not None进行测试;这使您可以轻松区分None和其他False-y值。你知道吗

*除非“魔法方法”以非标准方式实现

boolean operations上的Python语言参考说明了这一点:

In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: False, None, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true. (See the __nonzero__() special method for a way to change this.)

在您的例子中,由于root似乎是用户定义类型的实例(它有leftright成员,而内置类型没有),因此它要么实现了__nonzero__方法,要么None或者传入类似的“空”对象来表示没有“左”和“右”。你知道吗

在python中,您不必将某个东西与其他东西进行比较。你知道吗

if root默认情况下,检查变量root是否有内容,或者是否为空变量。 我来举例说明:

if ""
if 0
if None
if []
if {}
if ()

都会返回False吗

而其他任何值都将返回True。你知道吗

相关问题 更多 >