我正在尝试将递归python code for tarjan algorithm转换为scala,尤其是这一部分:
def tarjan_recursive(g):
S = []
S_set = set()
index = {}
lowlink = {}
ret = []
def visit(v):
index[v] = len(index)
lowlink[v] = index[v]
S.append(v)
S_set.add(v)
for w in g.get(v,()):
print(w)
if w not in index:
visit(w)
lowlink[v] = min(lowlink[w], lowlink[v])
elif w in S_set:
lowlink[v] = min(lowlink[v], index[w])
if lowlink[v] == index[v]:
scc = []
w = None
while v != w:
w = S.pop()
scc.append(w)
S_set.remove(w)
ret.append(scc)
for v in g:
print(index)
if not v in index:
visit(v)
return ret
我知道scala中有tarjan算法here或{a3},但它没有返回好的结果,并从python中翻译它来帮助我理解它。在
以下是我所拥有的:
^{pr2}$我知道这根本不是scala的方式(而且不干净…),但我计划在第一个版本开始工作时,慢慢地将它改为更具功能性的风格。在
现在,我得到了一个错误:
type mismatch; found : Unit required: Int
在这条线上
if(lowlink(v)==index(v)){
我想是从这条线传来的,但我不确定:
if( !(index.contains(w))
但调试起来真的很难,因为我不能直接打印我的错误。。。在
谢谢!在
这是一个迭代版本。它是Wikipedia中算法的递归版本的翻译。在
运行维基百科文章中的示例图:
^{pr2}$退货:
以下是Python的直译:
它在以下方面产生相同的输出:
^{pr2}$实现中最大的问题是返回类型}),并且在最后的
visit
(应该是Unit
,而不是{for
-理解中,迭代了图的项而不是图的键,但为了风格和清晰度,我做了一些其他的编辑(同时仍然保持基本形状)。在相关问题 更多 >
编程相关推荐