Python图实现

2024-07-08 15:27:06 发布

您现在位置:Python中文网/ 问答频道 /正文

嘿,目前正在编写一个教程,介绍如何使用邻接列表格式将图形实现到python中。我遇到一个例子,在“类图”中有一个缩进的包含函数。如下所示。在

def __contains__(self, n):
    return n in self.vertDict

verdict是一个通过类初始化的字典。我能要求解释一下这个功能的目的是什么吗?在

^{pr2}$

两鸟一石,我有点理解“加法”函数,但h和t的论点是什么?是在创造边缘吗?在

谢谢你!我一直在为这些实现而苦苦挣扎:'(


Tags: 函数inself图形列表return字典def
1条回答
网友
1楼 · 发布于 2024-07-08 15:27:06

Could i request an explanation of what this functions purpose is?

def __contains__(self, n):
    return n in self.vertDict

__contains__定义类的实例在innot in运算符(例如,x in foox not in foo)的右侧时的行为。[1]

考虑以下示例:

^{pr2}$

Two birds one stone, I sort of understand the 'addEdge' function but what are the arguments h and t? Is it creating edges?

h和{}似乎都是顶点。此方法似乎是在h和{}之间添加一条边,因此它看起来像(h)-(t)。在

# from the name, the method looks like it might be creating edges,
# but let's investigate further!
def addEdge(self,h,t):     

    # the first "give-away" is it's checking if
    # `h` is in `self.vertDict`
    if h not in self.vertDict:
        # if it *isn't* in `self.vertDict`, it adds it
        newV = self.addVert(h)

    # it does a similar check for `t`
    if t not in self.vertDict:
        newV = self.addVert(t)

    # it then adds a link, or edge between `h` and `t` here
    self.vertDict[h].addnewLink(self.vertDict[t])

资料来源:

[1]What does __contains__ do, what can call __contains__ function

相关问题 更多 >

    热门问题