Compact Anagram Code

The anagram question is one of the most basic and popular interview coding questions around for entry level cs/data science positions. Below is a quick two-line implementation of it for both Python and R.

R
input_list = c('bat', 'tabs', 'tab', 'mouse', 'cat', 'act', 'tac')
sorted_list = sapply(input_list, function(word) paste(sort(unlist(strsplit(word,split = ""))),collapse=""))
input_list[sapply(sorted_list, function(word) sum(sorted_list == word) > 1)]

Python
input_list = ['bat', 'tabs', 'tab', 'mouse', 'cat', 'act', 'tac']
sorted_list = [sorted(word) for word in input_list]
[input_list[i] for i, word in enumerate(sorted_list) if sorted_list.count(word) > 1]

Won’t win any speed contests but suffices for compactness and readability.