
Question:
I have a list of numbers:
<blockquote>6,12,24,25,7,27
</blockquote>How can I make it so that there is modulus at 26 so that if numbers greater than 26 appear in the list it should go back to 1?
For example, in this situation all numbers should be left alone except 27 and that should become 1.
This is the code I'm trying to run:
message = zip(message, newkeyword)
positions = [(alphabet.find(m), alphabet.find(n)) for m, n in message]
sums = [alphabet.find(m) + alphabet.find(n) for m, n in message]
#sums is were the numbers are stored
sums%=26
But I get the error:
<blockquote>TypeError: unsupported operand type(s) for %=: 'list' and 'int'
</blockquote>Any help is greatly appreciated.
Answer1:The modulo operator can only be applied to two numbers, not to a whole list. You have to apply it to each item, like this:
mod_sums = [s % 26 for s in sums]
Using a list comprehension you iterate through all numbers in the sums. In the new mod_sums
list you save the number s
modulo 26.
This basically is the same as:
mod_sums = []
for s in sums:
mod_sums.append(s % 26)
Only written in a cleaner and more <em>pythonic</em> way.
You could also add the modulo directly into the first list comprehension:
sums = [(alphabet.find(m) + alphabet.find(n)) % 26 for m, n in message]
Answer2:As an alternative, if you are willing/able to convert your list to a Numpy
array you can achieve this in a really simple and pythonic way (by just applying the modulo to the array):
>>> import numpy as np
>>> a = np.array([6,12,24,25,7,27])
>>> a
array([ 6, 12, 24, 25, 7, 27])
>>> a%26
array([ 6, 12, 24, 25, 7, 1])