HackerRank Python (Basic) certification
Missing Characters
One of the easier questions in the pool. If you know sets and string iteration, it takes five minutes. The marks are lost on output order and on small typos.
What the question asks
The input string contains only lowercase English letters and digits. Return a string made of every digit (0 to 9) and every lowercase letter (a to z) that does not appear in the input. The missing digits come first in ascending order, then the missing letters in alphabetical order.
Function to write
def missingCharacters(s):
# return a string
...The stub reads s, calls your function and writes the result.
Solution
def missingCharacters(s):
present = set(s)
result = ""
for ch in "0123456789abcdefghijklmnopqrstuvwxyz":
if ch not in present:
result += ch
return resultHow it works
set(s)keeps each character of the input once, and checkingch not in presenton a set is instant.- The loop walks a fixed string of all 36 allowed characters, digits first and letters after. Because that string is already in the required order, the result comes out in the right order with no sorting.
- Characters that are present are skipped. Everything else is added to
result. - If the input has every digit and letter, the loop adds nothing and the function returns an empty string.
You can also write string.digits + string.ascii_lowercase instead of typing the 36 characters. Typing them is fine as long as you type them correctly, which is the next point.
Mistakes that fail the hidden tests
- A typo in the reference string. One public solution uses
'01234567890', with 0 at both ends. When 0 is missing from the input, it gets added twice. Another has an extra h in its alphabet, with the same effect. Check your 36 characters, or use thestringmodule. - Letters before digits. The digits must come first.
- Returning a list.
str(['0', '1'])gives"['0', '1']", not"01". Join the characters into one string. - Using integers for digits.
1 in sraises “‘in <string>’ requires string as left operand, not int”. The digits in the string are characters, so compare with'1', not1. - Starting the digits at 1.
range(1, 10)leaves out 0.
Try it on sample data
print(missingCharacters("7985interdisciplinary12"))
print(missingCharacters("abc3458z"))Output from my run:
0346bfghjkmoquvwxz
012679defghijklmnopqrstuvwxy
In the first one, the input has the digits 1, 2, 5, 7, 8 and 9, so 0, 3, 4 and 6 are missing. Then come the letters that “interdisciplinary” does not use.