Search code examples
pythonencryptioncaesar-cipher

Cipher/Decipher Python Beginner Program


Question: Can someone edit my 2 lines of code?

Just wanted to point out that this is for a school assignment so I don't want to post all my code to prevent copy/plagiarism issues. Since I'm only having difficulties with a small requirement of the assignment, I don't think all my code is required anyways.

Requirement from the assgn I'm referring to:

Newx=ord(x)+3
Newx will be an integer. To find out what letter that integer represents you can use the chr function as in: actualLetter = chr(x) Write a function named cipher that takes a string and a key (integer). The function ciphers the string into another string and returns the new string. Note that when we reach 'z', and we want to add the key, we must 'roll' into the alphabet one more time, hence ord('z')+3 should give us ord('c').

When I run and test my program and input 'z', I don't get 'c', I get: screenshot of running program

My code for this portion of the program that results in this issue is:

example_string = letters[((ord(i)+key)%97)%26]
example2_string += letters[((ord(i)-key)%97)%26]

(example_string and example2_string are fake names)


Solution

  • You should not be performing anything modulo 97. Only perform modulo 97 if you have an alphabet of 97 characters.

    The correct way of doing this is:

    1. determine if the character is a letter;
    2. convert the letter to a number between 0 and the size of the alphabet (the common ABC is of course 26 characters in size);
    3. add or subtract the key value, modulo the size of the alphabet (for these kind of operations you can simply first add / subtract and then perform the modulus);
    4. convert the resulting number to a letter again, this is your ciphertext.

    So you would get:

    alphabetSize = ord('z') - ord('a') + 1
    
    k = 3
    c = 'z'
    
    if (ord(c) >= ord('a')) | (ord(c) <= ord('z')):
        n = ord(c) - ord('a')
        n = (n + k) % alphabetSize
        ctc = chr(n + ord('a'))
    else:
        ctc = c
    
    print ctc
    

    the magic (in this case encryption because of the + being used before key k) is of course in the 3 lines within the if statement. Those can be combined of course - if need be into one single line - but this is more neat.