我正在尝试实现一个因子图。我想从一个单独的文件中读取因子函数。不幸的是,当我从一个文件中读取一个函数只是为了测试时,我得到了错误:
eval(lines[0])(1,2,3)
File "<string>", line 1
def f(x0,x1,x2):
^
SyntaxError: invalid syntax
我的代码如下:
class Node:
def __init__(self,name,graph):
self.name = name
self.graph = graph
self.neighbourFactors=[];
class Factor:
def __init__(self,name,neighbours,graph):
self.name = name
self.value = 1
self.graph = graph
self.neighbourNodes=[];
class Graph:
def __init__(self,factorNumber,nodeNumber,factorNeighboursList):
self.factorNumber = factorNumber
self.factors=[Factor(i,factorNeighboursList[i],self) for i in range(factorNumber)]
self.nodes=[Node(i,self) for i in range(nodeNumber)]
factorNumber=0;
for neighbourNodes in factorNeighboursList:
for i in range(len(neighbourNodes)):
self.factors[factorNumber].neighbourNodes.append(self.nodes[int(neighbourNodes[i])]);
self.nodes[int(neighbourNodes[i])].neighbourFactors.append(self.factors[factorNumber])
factorNumber+=1;
def makeGraph(factorNumber,nodeNumber):
factorNeighboursList=[]*factorNumber
f = open('factorNeighboursInput.txt', 'r')
for line in f:
factorNeighboursList.append(line.split())
g=Graph(factorNumber,nodeNumber,factorNeighboursList)
return g
factorNumber=input('Please specify number of Factors:')
nodeNumber=input('Please specify number of Nodes:')
g=makeGraph(factorNumber,nodeNumber)
f = open('factorFunctionInput.txt', 'r')
lines=f.read().split(';')
print lines
eval(lines[0])(1,2,3)
我单独的函数输入文件是:
def f(x0,x1,x2):
return x0*x1*x2
;
def f(x1):
return x1+1
;
def f(x2):
return x2
;
def f(x3):
return x3+2
;