Search code examples
pythonrecursiontry-catchexcept

DNA Sequence Alignment in Python, Making a Cleaner Except Block


I'm writing a program in which you enter a short DNA sequence and a long one, and it tries to return the best possible alignment of the DNA sequences. The criteria are that if there is a gap, you subtract 10, if there is a match, you add 1, and if there is a mismatch, you subtract 1. The first part of my program scores the alignment, which works recursively by consistently deleting the first element of a long sequence and then scoring the alignment. My problem is that my except block is very ugly. Is there a way such that I can call back the original x before I continuously deleted elements from it?

lst=[]
def align_score(x,y):
    gap_score=(len(x)-len(y))*(-10)
    match_score=0
    mismatch_score=0
    ref=0
    try:
        for base in y:
            if y[ref]==x[ref]:
                match_score+=1
                ref+=1
            else:
                mismatch_score-=1
                ref+=1
        a=gap_score+match_score+mismatch_score
        lst.append(a)
        del(x[0])
        align_score(x,y)
    except:
        z=lst.index(max(lst))
        x='ACGTCCTTCATT'
        print x
        y='GTCTCATG'
        print "%s%s"%(" "*z, y)

x=list('ACGTCCTTCATT')
y=list('GTCTCATG')
align_score(x,y)

Solution

  • Two ways you can easily do this:

    • Assign variables x_orig = x and y_orig = y in your function as the first lines then calling x_orig and y_orig in the except block.
    • Make STRAND_X and STRAND_Y global constants outside the function scope, call the function with the constants as arguments, manipulate the local variables x and y in the try block, and then refer to the global constants in the except block.