Question

I am trying to implement a factor graph. I would like to read the factor functions from a sperate file. Unfortunately when I read a function from a file just for test I get the error:

    eval(lines[0])(1,2,3)
  File "<string>", line 1
    def f(x0,x1,x2):
      ^
SyntaxError: invalid syntax

My code is as follows:

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)

my separate input file for functions is:

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
;
Était-ce utile?

La solution

I think in case of calling eval with multiple line eval function, it fails. You should use eg.exec instead of eval:solution

Furthermore i think you have to call the functions, the definition doesn't seems enough:

    def f(x0,x1,x2):
       return x0*x1*x2

    f(x0,x1,x2)
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top