gpt4 book ai didi

Python - 如何编写更高效的 Pythonic reduce?

转载 作者:太空狗 更新时间:2023-10-29 19:25:54 25 4
gpt4 key购买 nike

我正在尝试构建一个非常轻量级的 Node 类来用作基于 Python 的层次结构搜索工具。请参阅下面的定义。

from functools import reduce
from operator import or_


class Node:

def __init__(self, name):
self.name = name
self.children = []

def add_child(self, child_node):
self.children.append(child_node)

def contains(self, other_node):
if self == other_node:
return True
elif other_node in self.children:
return True
else:
return reduce(or_, [child.contains(other_node)
for child in self.children], False)

def is_contained_by(self, other_node):
return other_node.contains(self)

def __eq__(self, other_node):
return self.name == other_node.name

def __de__(self, other_node):
return self.name != other_node.name

contains 似乎是函数式编程的教科书案例(直接来自 Why Functional Programming Matters )。

问题:是否有更高效或Pythonic 的方式来编写contains?我知道 map 通常被列表理解所取代,但我还没有看到更好的方法来执行基于 reduce 的递归。

谢谢,

迈克

===已编辑...这是考虑到答案和评论的重做类(class)===

class Node:

def __init__(self, name):
self.name = name
self.children = []

def add_child(self, child_node):
# Hattip to lazyr for catching this.
if self.contains(child_node) or child_node.contains(self):
raise TreeError('A relationship is already defined.')
else:
self.children.append(child_node)

def contains(self, other_node):
# Hattip to lazyr for pointing out any() and to Jochen Ritzel for
# eliminating the silly child check.
return (self == other_node or
any(child.contains(other_node) for child in self.children))

def is_contained_by(self, other_node):
return other_node.contains(self)

def __eq__(self, other_node):
return self.name == other_node.name

def __de__(self, other_node):
return self.name != other_node.name

def __repr__(self):
return self.name

最佳答案

我认为(未测试)您应该像这样使用 any 而不是 reduce,它将在第一次命中时停止:

return any(child.contains(other_node) for child in self.children)

顺便说一下,当 a == b 时,您的意思是 a.contains(b) 返回 False len(a.children) > 0?

编辑:如果你的树包含一个循环,像这样:

a = Node("a")
b = Node("b")
a.add_child(a)
a.add_child(b)

然后

a.contains(b)

会使程序崩溃。您可能需要在 containsadd_child 中检查这一点,具体取决于您最常用的是哪个。

关于Python - 如何编写更高效的 Pythonic reduce?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5353727/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com