Home > Net >  Encoding a string using function
Encoding a string using function

Time:10-14

I created the following function to pair each letter in the alphabet with its corresponding encoded letter based on a given shift:

alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']


def build_cipher(shift):
    '''
    Description: takes in shift (an integer representing the amount the letter key in the dictionary is shifted from its corresponding letter) and returns a dictionary containing all letters and their corresponding letters after the shift. This is achieved through subtracting the shift from the number corresponding to the letter, and using modulo 26.
    
    >>> build_cipher(-3)
    {'a': 'x', 'b': 'y', 'c': 'z', 'd': 'a', 'e': 'b', 'f': 'c', 'g': 'd', 'h': 'e', 'i': 'f', 'j': 'g', 'k': 'h', 'l': 'i', 'm': 'j', 'n': 'k', 'o': 'l', 'p': 'm', 'q': 'n', 'r': 'o', 's': 'p', 't': 'q', 'u': 'r', 'v': 's', 'w': 't', 'x': 'u', 'y': 'v', 'z': 'w'}
    '''
    return {alphabet[i]: alphabet[(i   shift) % 26] for i in range(0, 26)}

Next I need to define a function encode that takes in text and shift, and returns the text encoded. I also need to use my build_cipher function in order to do this. So far I have:

def encode(text, shift):
    '''
    Description: takes in a text string and shift. Returns the text string encoded based on the shift.
    
    >>> encode('test', -4)
    
    >>> encode('code', 5)
    
    '''
    #return (text[(i   shift) % 26] for i in range(0,26))
    #return (build_cipher(shift) for text in alphabet)
    #return (build_cipher(shift) for text in range(0,26))

Each of my attempts at the return statement are in comments at the bottom. None are working correctly and I am unsure of how to exactly do this since build_cipher returns as a dictionary. Any tips on how I could achieve this are appreciated.

CodePudding user response:

You already have created your cipher building function, now let's use it to create the cipher and apply it to each character in your text. I used here get to enable keeping a character that is not in the cipher unchanged.

def encode(text, shift):
    cipher = build_cipher(shift)
    return ''.join(cipher.get(c, c) for c in text)

Example:

>>> encode('good morning', 4)
'kssh qsvrmrk'

>>> encode('kssh qsvrmrk', -4)
'good morning'

NB. your code is currently not handling capital letters, that's something you might want to fix ;)

  • Related