我是一名新的程序员,正在学习斯坦福大学关于edX的算法课程
编程任务之一是使用Kosaraju算法在一个有1000000个顶点的图上查找强连通的组件。我的实现是从教科书的伪代码到Python的最基本的翻译,它在较小的图形上运行良好,因此我认为它是正确的
Python的默认递归限制是1000,它达到了这个限制
我已经尝试了sys.setrecursionlimit(1000000)
,但这没有帮助,相反,我得到了“进程已完成,退出代码为-1073741571”,这是一个堆栈溢出
我发现这两个页面用于增加堆栈大小限制,但不确定如何使用它们:Set stack size,ulimit command
另一个相关信息是Python没有优化尾部递归,但我不确定这是否适用于我的代码,因为它目前是这样的
G = {}
for i in range(1, 875715):
G[i] = [0]
for l in open('SCC.txt'):
items = list(map(int, l.split()))
G[items[0]].append(items[1])
Grev = {}
for i in range(1, 875715):
Grev[i] = [0]
for l in open('SCC.txt'):
items = list(map(int, l.split()))
Grev[items[1]].append(items[0])
def TopoSort(G):
for v in G:
if G[v][0] == 0:
DFStopo(G, v)
def DFStopo(G, s):
G[s][0] = 1
global orderedVertexList
for v in G[s][1:]:
if G[v][0] == 0:
DFStopo(G, v)
orderedVertexList.insert(0, s)
def Kosaraju(G, Grev):
TopoSort(Grev)
global numSCC
for v in orderedVertexList:
if G[v][0] == 0:
numSCC = numSCC + 1
DFSSCC(G, v)
def DFSSCC(G, s):
G[s][0] = 1
global SCC
SCC.append(numSCC)
for v in G[s][1:]:
if G[v][0] == 0:
DFSSCC(G, v)
numSCC = 0
orderedVertexList = []
SCC = []
Kosaraju(copy.deepcopy(G), copy.deepcopy(Grev))
目前没有回答
相关问题 更多 >
编程相关推荐