#format python """ nussinov.py NussinovAlgorithm code python input.txt: GGGAAAUCG c:\workplace> python nussinov.py output.txt output.txt (which will be created in the same directory): (2,9) (3,8) (4,7) """ """nussinov""" class NussinovMatrix: def __init__(self, rnaseq): self.rnaseq = rnaseq self.L = len(rnaseq) self.matrix = [] for i in range(self.L): self.matrix.append(range(self.L)) for i in range(self.L): for j in range(self.L): self.matrix[i][j] = 'n' self.fillInitialMatrix() def fillInitialMatrix(self): for i in range(1, self.L): self.matrix[i][i-1] = 0 for i in range(self.L): self.matrix[i][i] = 0 def fillMatrix(self): endOfSeq = self.L + 1 for oneDiagonal in range(1, endOfSeq): i = 1 for oneCell in range(1, endOfSeq): j = i + oneDiagonal if j > self.L: break else: self.writeValue(i, j) i += 1 endOfSeq -= 1 def writeValue(self, i, j): unpairi = self.getValue(i+1, j) unpairj = self.getValue(i, j-1) pair = self.getValue(i+1, j-1) + self.score(i, j) ks = range(i+1, j) if ks == []: bifurcation = 0 else: bifurcations = [] for k in ks: case = self.getValue(i, k) + self.getValue(k+1, j) bifurcations.append(case) bifurcation = max(bifurcations) result = max(pair, unpairi, unpairj, bifurcation) self.setValue(i, j, result) def score(self, ai, aj): i = self.rnaseq[ai-1] j = self.rnaseq[aj-1] RNAComplementary = {'A':'U', 'U':'A', 'G':'C', 'C':'G'} return RNAComplementary[i] == j def getInitialMatrix(self): return self.matrix def getFinalMatrix(self): self.fillMatrix() return self.matrix def getValue(self, i, j): return self.matrix[i-1][j-1] def setValue(self, i, j, aValue): self.matrix[i-1][j-1] = aValue class Nussinov(NussinovMatrix): def __init__(self, aRnaseq): NussinovMatrix.__init__(self, aRnaseq) matrix = self.getFinalMatrix() self.stack = [] self.stack.append((1, self.L)) self.basepair = [] self.iterateTraceback() def iterateTraceback(self): while 1: try: popedItem = self.stack.pop() except IndexError: break self.doRecursion(popedItem) def doRecursion(self, popedItem): i, j = popedItem if i >= j: pass elif self.getValue(i+1, j) == self.getValue(i,j): self.stack.append((i+1, j)) elif self.getValue(i, j-1) == self.getValue(i,j): self.stack.append((i, j-1)) elif self.getValue(i+1, j-1) + self.score(i,j) == self.getValue(i,j): self.basepair.append((i,j)) self.stack.append((i+1, j-1)) else: ks = range(i+1, j) for k in ks: if self.getValue(i,k) + self.getValue(k+1,j) == self.getValue(i,j): self.stack.append((k+1,j)) self.stack.append((i,k)) break def getBasePair(self): return self.basepair def writeResult(): inputRnaTotal = '' while 1: try: inputRna=raw_input() except EOFError: break if not inputRna: break inputRnaTotal += inputRna.strip() a = Nussinov(inputRnaTotal) for each in a.getBasePair(): print each if __name__=='__main__': writeResult()