How does .rjust() work and why it places characters relative to previous one, not to first character - placed most to left - or to left side of screen?

Peter Otten __peter__ at web.de
Mon Aug 20 08:45:28 EDT 2012


crispy wrote:

> Thanks, i've finally came to solution.
> 
> Here it is -> http://codepad.org/Q70eGkO8
> 
> def pairwiseScore(seqA, seqB):
> 
>     score = 0
>     bars = [str(' ') for x in seqA] # ...
>     length = len(seqA)
>     similarity = []
> 
>     for x in xrange(length):
> 
>         if seqA[x] == seqB[x]: # ...
>             if (x >= 1) and (seqA[x - 1] == seqB[x - 1]): # ...
>                 score += 3
>                 similarity.append(x)
>             else:
>                 score += 1
>                 similarity.append(x)                
>         else:
>             score -= 1
> 
>     for x in similarity:
>         bars[x] = '|' # ... 
> 
>     return ''.join((seqA, '\n', ''.join(bars), '\n', seqB, '\n', 'Score: 
', str(score)))
> 

Python has a function zip() that lets you iterate over multiple sequences 
simultaneously. Instead of

for i in xrange(len(a)):
    x = a[i]
    y = b[i]
    ...

you can write

for x, y in zip(a, b):
    ...

Also, you can build the bar list immediately and avoid the similarity list.

With these changes:

def pairwise_score(a, b):
    score = 0
    was_equal = False
    bars = []
    for x, y in zip(a, b):
        equal = x == y
        if equal:
            bars.append("|")
            if was_equal:
                score += 3
            else:
                score += 1
        else:
            bars.append(" ")
            score -= 1
        was_equal = equal
    print a
    print "".join(bars)
    print b
    print "Score:", score

If you want to take this even further you can use a score matrix instead of 
if ... else:

def pairwise_score(a, b):
    score = 0
    was_equal = False
    bars = []
    matrix = [[-1, 1], [-1, 3]]
    for x, y in zip(a, b):
        equal = x == y
        score += matrix[was_equal][equal]
        bars.append(" |"[equal])
        was_equal = equal
    print a
    print "".join(bars)
    print b
    print "Score:", score




More information about the Python-list mailing list