Skip to content

Instantly share code, notes, and snippets.

@tugloo1
Last active June 1, 2018 23:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tugloo1/4805d9f4876f2f177410f1bd026993ea to your computer and use it in GitHub Desktop.
Save tugloo1/4805d9f4876f2f177410f1bd026993ea to your computer and use it in GitHub Desktop.
""" Coding Test: Group all the anagrams into sets
"""
def get_unique_anagram_key(anagram):
anagram = anagram.replace(' ', '') # Get rid of any spaces
split_anagram = sorted(list(anagram))
key = ''.join(split_anagram)
return key
def group_list_by_anagrams(input_list):
""" Should return a set of set of anagrams.
:param input_list:
:return:
:rtype: list[tuple[str, str]]
"""
output_dict = {}
for anagram in input_list:
key = get_unique_anagram_key(anagram)
if key in output_dict:
output_dict[key].append(anagram)
else:
output_dict[key] = [anagram]
output_list = []
for values in output_dict.values():
output_list.append(tuple(values))
return output_list
input_possible_anagrams = ['dormitory',
'eleven plus two',
'cider',
'dirty room',
'bored',
'robed',
'twelve plus one',
'cried',
'alone']
valid_output = [('dormitory', 'dirty room'),
('eleven plus two', 'twelve plus one'),
('cider', 'cried'),
('bored', 'robed'),
('alone',)]
seen_output = group_list_by_anagrams(input_possible_anagrams)
# Checking if seen output is the same as valid output
assert valid_output.__len__() == seen_output.__len__(), 'The length of expected and seen are not the same'
for toople in valid_output:
assert toople in seen_output, '{0} not seen in seen_output'.format(toople.__str__())
print('Test passed')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment