python - 基于变量存在的while循环中使用or和管道的写入条件差异
问题描述
我正在尝试编写一个函数来inorder
遍历binary tree
. 我的功能如下:
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def inorderTraversal(root):
"""
:type root: TreeNode
:order: List[int]
"""
stack = []
order = []
while stack or root:
if root:
stack.append(root)
root = root.left
else:
current_node = stack.pop()
order.append(current_node.val)
root = current_node.right
return order
现在,我对这条线感到困惑
while stack or root: # this works fine
我尝试以不同的方式编写如下:
while stack | root:
这导致函数失败并出现以下错误
TypeError: unsupported operand type(s) for |: 'list' and 'TreeNode'
大多数时候,我|
用来比较if statement
数据帧或数据帧中的条件indexing
,它一直运行良好。
|
和 和有什么不一样or
?为什么在这种特殊情况下会失败?
解决方案
|
是按位逻辑运算符,它可以被自定义类覆盖。or
是规范逻辑运算符;它不能被覆盖,它只适用于bool
s。
您要询问的行利用了bool
对列表类型和一般对象的隐式转换。如果stack
为空,bool(stack)
将返回False
(True
否则)。同样,如果root
绑定到一个None
对象,那么bool(root)
将返回False
(True
否则)。
while stack or root
因此等价于while len(stack) > 0 or root is not None
。
推荐阅读
- ansible - 设置带有 win_shell 模块错误的 Ansible playbook
- kubernetes - Kubernetes 部署失败 - 如何检查?
- excel - Excel VBA宏更改单元格中的文本内容
- c++ - C++ 输入文件流无法从文件中读取字符串
- javascript - node.js 等待尚未可用的承诺
- javascript - 使用悬停事件更改班级
- python - Python Simple-Salesforce 更改“并发模式”
- html - 右边框和左边框高度与元素 HTML-CSS 上的填充不匹配
- github - 您如何在供应商 DIR 中创建一个 Magento 2 管理主题作为存储库?
- java - 如何在 vaadin 14 中重置应用布局?