Reputation: 281
I am currently learning python and encountered this function.
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
I'm quite confused to what it means by "if not root". What condition is it trying to give? if "root" is not what? What comparison is "if" trying to make?
UPDATE: Root is a binary tree which has the subtrees self.left and self.right. In can also be None. This is the case if the node is a leaf.
Upvotes: 1
Views: 80
Reputation: 122086
In Python, if expr:
really means if bool(expr):
, i.e. it evaluates whatever expression is given to it then converts the result to a boolean (in many cases, of course, it's already a boolean, e.g. x > y
will be True
or False
*).
The built-in types have rules for boolean evaluation; in short, empty containers and sequences (dict
, list
, tuple
, set
, str
, etc.) plus zero numerical values (0
, 0.0
, 0j
, etc.) and None
evaluate False
-y, anything else is considered True
-y. User-implemented types usually follow this convention.
This lets if root
be a handy shortcut for e.g. if root != 0
or if len(root) > 0
, depending on what type of object root
is expected to be. Note that None
is usually, per the style guide, tested with if name is not None
; this lets you easily distinguish between None
and other False
-y values.
* Unless the "magic methods" are implemented in a non-standard way
Upvotes: 1
Reputation: 23255
The Python language reference on boolean operations explains this:
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.)
In your case, since root
seems to be an instance of a user-defined type (it has left
and right
members, which no built-in type has), it either has the __nonzero__
method implemented, or None
or a similar "empty" object is passed in to signal that there is no "left" and "right".
Upvotes: 1
Reputation: 59274
In python, you dont necessarily have to compare something to something else.
if root
checks, by default, if the variable root has a content, or if it is an empty variable.
Let me explain you via examples:
if ""
if 0
if None
if []
if {}
if ()
would all return False
While any other values would return True.
Upvotes: 3