how to check numbers in a list in python

Here is a cleaned-up version:

from itertools import cycle

BASE = ord('a') - 1

def str_to_nums(s):
    Convert a lowercase string to a list of integers in [1..26]
    return [ord(ch) - BASE for ch in s]

def nums_to_str(nums):
    Convert a list of integers in [1..26] back to a lowercase string
    return "".join(chr(n + BASE) for n in nums)

def shift_cypher(string, key_string):
    nums = str_to_nums(string)
    key  = str_to_nums(key_string)
    # x % 26 returns a value in [0..25]
    # but we want a value in [1..26]
    # so after % (mod) we have to add one
    # so _before_ we add we have to subtract one
    # so that the result comes out right!
    encrypted = [((num + k - 1) % 26) + 1 for num,k in zip(nums, cycle(key))]
    return nums_to_str(encrypted)

def main():
    text = input("Text to encode: ")
    key  = input("Key to encode by: ")
    print("Result is", shift_cypher(text, key))

if __name__ == "__main__":

which runs like

Text to encode: hello
Key to encode by: aaa
Result is ifmmp

Browse More Popular Posts

Leave a Comment