Skip to content

Question 43

Given an input string s and a dictionary d such that all the keys and values are single alphabet characters in uppercase, complete function encrypt() using valid Python expressions/statements such that it changes all the characters in s from the keys to the values in d. If a character c is not a key of d, that character remains unchanged.

1
2
3
4
5
6
7
8
def encrypt(d,s):
    output = ''
    for c in _____1_____:
        if _____2_____:
            output = _____3_____
        else:
            output = _____4_____
    return output

Here is a sample run:

>>> print(encrypt({'A':'C','Q':'E','N':'M'},"BANANA"))
BCMCMC
>>> print(encrypt({'P':'C','T':'E','N':'M'},"PYTHONIDLE"))
CYEHOMIDLE

Note that your code needs to be syntactically correct to gain marks. You cannot use any semi-colon(;) and we will deduct marks if your answer is too long.

Model Solution
1
2
3
4
5
6
7
8
def encrypt(d,s):
    output = ''
    for c in s:
        if c in d.keys():
            output = output + d[c]
        else:
            output = output + c
    return output
  • Blank 1: s
    • Iterate through each character in s, keeping the character at each iteration in c
  • Blank 2: c in d.keys()
    • Check if character c is one of the keys in d
  • Blank 3: output + d[c]
    • d[c] represents the value mapped to key represented by character c in dictionaryd; do this if c is a key in d
  • Blank 4: output + c
    • Do this if c is not a key in d

Another set of acceptable answers for Blanks 2-4:

  • Blank 2: c not in d.keys()
  • Blank 3: output + c
  • Blank 4: output + d[c]