我在 LeetCode 上查看别人的解决方案时遇到了一些代码:
def findLeaves(self, root):
if not root: return []
kids = map(self.findLeaves, (root.left, root.right))
return map(lambda l, r: (l or []) + (r or []), *kids) + [[root.val]]
我发现它只适用于 Python 2 而不适用于 3,所以我做了以下调试:
蟒蛇2:
a = [[],[]]
b = map(lambda l, r: (l or []) + (r or []), *a) + [[4]]
c = map(lambda l, r: (l or []) + (r or []), *a) + [[5]]
d = map(lambda l, r: (l or []) + (r or []), *[b,c]) + [[2]]
e = [[3]]
f = map(lambda l, r: (l or []) + (r or []), *[d,e]) + [[1]]
print f
蟒蛇3:
a = [[],[]]
b = list(map(lambda l, r: (l or []) + (r or []), *a)) + [[4]]
c = list(map(lambda l, r: (l or []) + (r or []), *a)) + [[5]]
d = list(map(lambda l, r: (l or []) + (r or []), *[b,c])) + [[2]]
e = [[3]]
f = list(map(lambda l, r: (l or []) + (r or []), *[d,e])) + [[1]]
print(f)
上面的代码[[4, 5, 3], [2], [1]]在 Python 2(正确)和[[4, 5, 3], [1]]Python 3(错误)中返回。
*[d,e]is [[4,5], [2]] [[3]],在 Python 2 中,处理[[2]]时它将自动分配None给 lambda 表达式中的 r。但是在 Python 3 中,它会跳过记录。
我还发现,在Python 2,假如我换f到list(map(lambda l, r: (l or []) + (r or []), *itertools.zip_longest(d,e))) + [[1]],它会工作。但是,它会弄乱 b 和 c 的情况。
谁能解释一下修复代码的正确方法是什么?另外,我调试的方式非常愚蠢(我总是使用打印),有没有更好的调试代码的方法?我是 Python 新手并使用 Jupyter notebook 来运行我的代码。
慕后森
相关分类