Search code examples
pythonpython-3.xencryptionmethodsone-liner

Is there any way to make the below code in one-line


I am trying a cipher technique (One Time Pad), I got the solution but want to make it one-line. Here's a sample input and output respectively.INPUT(TEXT) = 'HELLO', KEY = 'XMCKL', OUTPUT(CIPHERTEXT) = 'EQNVZ'.

def ciphertextFor(text, key):
    cpt = []
    for i in range(len(text)):
        cpt.append(chr((ord(text[i])+ord(key[i])) % 26+65))
    return ''.join(cpt)
    # return ''.join(chr((ord(text[j])+ord(key[j])) % 26+65)) for j in range(len(text)))

Solution

  • Try this with a simple list comprehension directly from your function above -

    text, key = 'ajshwhsuhe','amchaksheo'
    
    cipher = ''.join([chr((ord(text[i])+ord(key[i])) % 26+65) for i in range(len(text))])
    
    print(cipher)
    
    'MHGAIDWNXE'