I have constructed a Vigenere cipher function that works reasonably well, except for the fact that it does not pass the coding test that I'm required to run it through.
This is due to the fact that I'm using the ordinal values, while the test is expecting me to use a function to just rotate through a string letters, I think.
I have already run through the issue of dealing with non-alpha characters and got it to work with both upper case and lower case characters. However, it seems to fall apart if the key has any variance of upper case or lower case characters i.e. the key is lower case but the plain text is upper.
def encrypt(text, key):
cipher_text = []
key = list(key)
if len(text) == len(key):
return(key)
else:
for i in range(len(text) -
len(key)):
key.append(key[i % len(key)])
for i in range(len(text)):
a = text[i]
if a.isalpha() and a.islower():
x = ((ord(text[i]) + ord(key[i])-97) % 26 + 97)
cipher_text.append(chr(x))
elif a.isalpha() and a.isupper():
x = ((ord(text[i]) + ord(key[i])-65) % 26 + 65)
cipher_text.append(chr(x))
else:
cipher_text.append(a)
return("" . join(cipher_text))
def main():
mess = input(str("What is message?"))
key = input("What is key?")
print(encrypt(mess, key))
if __name__ == '__main__':
main()
For vigenere.encrypt('BaRFoo', 'BaZ')
You should have returned this:
'CaQGon'
But you actually returned this:
'PtDTha'