Back to Freecodecamp

Step 85

curriculum/challenges/english/blocks/learn-string-manipulation-by-building-a-cipher/65552a9593755e1fb2f5ab50.md

latest1.9 KB
Original Source

--description--

Define another function named decrypt with the same parameters as encrypt. This time return vigenere(message, key, -1).

--hints--

You should define a new function called decrypt.

js
({ test: () => assert(runPython(`
    import inspect
    inspect.isfunction(decrypt)
  `))
})

Your decrypt function should take message and key as the parameters.

js
({ test: () => assert(runPython(`
    import inspect
    sig = inspect.signature(decrypt)
    str(sig) == "(message, key)"
  `))
})

Your decrypt function should return vigenere(message, key, -1).

js
({ test: () => {
    const commentless_code = __helpers.python.removeComments(code);
    const {function_body} = __helpers.python.getDef(commentless_code, "decrypt");
    assert(function_body.match(/return\s+vigenere\s*\(\s*message\s*,\s*key\s*,\s*-\s*1\s*\)/));
  }
})

--seed--

--seed-contents--

py
text = 'Hello Zaira!'
custom_key = 'python'

def vigenere(message, key, direction=1):
    key_index = 0
    alphabet = 'abcdefghijklmnopqrstuvwxyz'
    final_message = ''

    for char in message.lower():

        # Append any non-letter character to the message
        if not char.isalpha():
            final_message += char
        else:        
            # Find the right key character to encode/decode
            key_char = key[key_index % len(key)]
            key_index += 1

            # Define the offset and the encrypted/decrypted letter
            offset = alphabet.index(key_char)
            index = alphabet.find(char)
            new_index = (index + offset*direction) % len(alphabet)
            final_message += alphabet[new_index]
    
    return final_message
--fcc-editable-region--
def encrypt(message, key):
    return vigenere(message, key)
    
encryption = vigenere(text, custom_key)
print(encryption)
decryption = vigenere(encryption, custom_key, -1)
print(decryption)
--fcc-editable-region--