How to Find the Missing Alphabets in Python

The challenge

Task

Given string s, which contains only letters from a to z in lowercase.

A set of the alphabet is given by abcdefghijklmnopqrstuvwxyz.

2 sets of alphabets mean 2 or more alphabets.

Your task is to find the missing letter(s). You may need to output them by the order a-z. It is possible that there is more than one missing letter from more than one set of alphabet.

If the string contains all of the letters in the alphabet, return an empty string ""

Example

For s='abcdefghijklmnopqrstuvwxy'

The result should be 'z'

For s='aabbccddeeffgghhiijjkkllmmnnooppqqrrssttuuvvwwxxyy'

The result should be 'zz'

For s='abbccddeeffgghhiijjkkllmmnnooppqqrrssttuuvvwwxxy'

The result should be 'ayzz'

Input/Output

  • [input] string s

Given string(s) contains one or more sets of alphabets in lowercase.

  • [output] a string

Find the letters contained in each alphabet but not in the string(s). Output them by the order a-z. If the missing alphabet is repeated, please repeat them like "bbccdd", not "bcdbcd"

The solution in Python code

Option 1:

from collections import Counter
from string import ascii_lowercase

def missing_alphabets(s):
    c = Counter(s)
    m = max(c.values())
    return ''.join(letter * (m - c[letter]) for letter in ascii_lowercase)

Option 2:

def missing_alphabets(s):
  return ''.join(sorted(c * (max(s.count(x) for x in s) - s.count(c)) for c in 'abcdefghijklmnopqrstuvwxyz'))

Option 3:

def missing_alphabets(s):
    doc = {e:s.count(e) for e in 'abcdefghijklmnopqrstuvwxyz'}
    mx  = max(doc.values())
    return ''.join(k * (mx - v) for k,v in doc.items() if v < mx)

Test cases to validate our solution

test.it("Basic Tests")
test.assert_equals(missing_alphabets("abcdefghijklmnopqrstuvwxy"),"z")
test.assert_equals(missing_alphabets("abcdefghijklmnopqrstuvwxyz"),"")
test.assert_equals(missing_alphabets("aabbccddeeffgghhiijjkkllmmnnooppqqrrssttuuvvwwxxyy"),"zz")
test.assert_equals(missing_alphabets("abbccddeeffgghhiijjkkllmmnnooppqqrrssttuuvvwwxxy"),"ayzz")