PYTHON/Python
[Python] return or / and
민트맛녹차
2022. 8. 30. 21:52
파이썬 코테 공부 중 return 에 and 나 or 을 쓸 수 있다는 사실을 알았다.
def mergeTrees1(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]:
if root1 and root2:
node = TreeNode(root1.val + root2.val)
node.left = self.mergeTrees1(root1.left, root2.left)
node.right = self.mergeTrees1(root1.right, root2.right)
return node
else:
return root1 or root2
return A or B
if x is false, then y, else x
즉, A가 거짓이면 B, 나머지 경우는 A를 return 한다.
return A and B
if x is false, then x, else y
즉, A가 거짓이면 A, 나머지 경우는 B를 return 한다.
따라서 위의 코드는 not( root1 and root2 )의 경우, root1이 None이면 root2를 , root2가 None이면 root1을, 둘다 None인 경우는 None을 return 한다.
참조
https://stackoverflow.com/questions/4477850/and-or-operators-return-value