pythonmathmodulorosalind

Why does modulo have to be performed during every iteration?


This is one of those questions where I stumbled upon the right answer, but I don't understand why it's the right one and Wikipedia didn't help. For Rosalind, I wrote a simple script for getting the number of all the possible RNA sequences from a protein string (modulo 1,000,000). I know it's not the most efficient possible code (partly because I recycle bits from previous things I've made), but here it is:

protein = """<large protein string>"""
protein = ''.join(protein.split('\n'))

translate = {'UUU' : 'F','CUU' : 'L','AUU' : 'I','GUU' : 'V','UUC' : 'F','CUC' : 'L','AUC' : 'I','GUC' : 'V','UUA' : 'L','CUA' : 'L','AUA' : 'I','GUA' : 'V','UUG' : 'L','CUG' : 'L','AUG' : 'M','GUG' : 'V','UCU' : 'S','CCU' : 'P','ACU' : 'T','GCU' : 'A','UCC' : 'S','CCC' : 'P','ACC' : 'T','GCC' : 'A','UCA' : 'S','CCA' : 'P','ACA' : 'T','GCA' : 'A','UCG' : 'S','CCG' : 'P','ACG' : 'T','GCG' : 'A','UAU' : 'Y','CAU' : 'H','AAU' : 'N','GAU' : 'D','UAC' : 'Y','CAC' : 'H','AAC' : 'N','GAC' : 'D','UAA' : 'Stop','CAA' : 'Q','AAA' : 'K','GAA' : 'E','UAG' : 'Stop','CAG' : 'Q','AAG' : 'K','GAG' : 'E','UGU' : 'C','CGU' : 'R','AGU' : 'S','GGU' : 'G','UGC' : 'C','CGC' : 'R','AGC' : 'S',
'GGC' : 'G','UGA' : 'Stop','CGA' : 'R','AGA' : 'R','GGA' : 'G','UGG' : 'W','CGG' : 'R','AGG' : 'R','GGG' : 'G',
}
aminos = translate.values()
sample = [l for l in protein] + ['Stop']

score = []
for s in sample:
    c = aminos.count(s)
    score.append(c)

import math
result = reduce(lambda x, y: x*y, score) % 1000000
print result

This computes the total number of RNA sequences and takes the modulo of the final result (or so I think). I got the wrong answer twice before I decided to try this:

import math
result = reduce(lambda x, y: x*y % 1000000, score)
print result

This apparently produced the correct answer. Why does a modulo have to be performed at every x*y? Am I not understanding modulo or am I not understanding Python?

EDIT: Sorry, typo.


Solution

  • The difference between

    reduce(lambda x, y: x*y, score) % 1000000
    

    and

    reduce(lambda x, y: x*y % 1000000, score)
    

    Is that the first has to work with longs up to the product of all the values in score whereas the second will work with values no larger than max(score) * 999999.

    Arbitrarily large integers cannot be stored in finite memory, nor can their product be calculated in constant time, so you're far more likely to hit an OutOfMemoryError or take a very long time with the first option