Skip to content

Instantly share code, notes, and snippets.

@iMel408
Created May 22, 2019 18:45
Show Gist options
  • Save iMel408/964b6893fb14f895db402971b8fa53a3 to your computer and use it in GitHub Desktop.
Save iMel408/964b6893fb14f895db402971b8fa53a3 to your computer and use it in GitHub Desktop.
just for fun
'''Fun with Anagrams:
QUESTION DESCRIPTION
Two strings are anagrams if they are permutations of each other. For example, "aaagmnrs" is an anagram of "anagrams".
Given an array of strings, remove each string that is an anagram of an earlier string, then return the remaining array
in sorted order.
For example, given the strings s = ['code', 'doce', 'ecod', 'framer', 'frame'], the strings 'doce' and 'ecod' are both
anagrams of 'code' so they are removed from the list. The words 'frame' and 'framer' are not anagrams due to the extra
'r' in 'framer', so they remain. The final list of strings in alphabetical order is ['code', 'frame', 'framer'].
'''
words = ['code', 'doce', 'ecod', 'framer', 'frame']
# words_set = {''.join(sorted(word)): word2 for word2 in words for word in words if ''.join(sorted(word)) == ''.join(sorted(word2))}
# print(words_set) # nope
# for i, word in enumerate(sorted(words)):
# for x in range(len(words)):
# if sorted(list(words[x])) != sorted(list(word)):
# print(words[i])
#
# result = {word: sorted(list(word)) for word in words}
# print(result) # nope
# word = 'code'
# print(sorted(word))
# sorted_word = ''.join(sorted(word)
# print(sorted_word)
# word_set = {''.join(sorted(word)) for word in words}
def del_anagrams(lst):
# word_set = {''.join(sorted(word)) for word in words}
word_set = set()
result = []
for word in lst:
if ''.join(sorted(word)) not in word_set:
result.append(word)
word_set.add(''.join(sorted(word)))
return sorted(result)
print(del_anagrams(words)) # It Worked!!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment