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.
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
- Blank 1:
s- Iterate through each character in
s, keeping the character at each iteration inc
- Iterate through each character in
- Blank 2:
c in d.keys()- Check if character
cis one of the keys ind
- Check if character
- Blank 3:
output + d[c]d[c]represents the value mapped to key represented by charactercin dictionaryd; do this ifcis a key ind
- Blank 4:
output + c- Do this if
cis not a key ind
- Do this if
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]