Given a word and a list of words, I have to find the list elements/words that can be built using letters (count of letter matters) of the given word. I have tried to use Counter
object from collections and a definition of python 2.7's cmp()
function (I'm using 3.6.5).
I have since come to realize this approach seems to be bad practice for such a problem (Earlier, I was trying to use counter object-dictionaries to compare). The reason my program doesn't work is because the compare_fn relies on '>','<' operations between lists, which give result based on lexicographical order (referred from here). So even though 'raven' can be made from 'ravenous', the program below will fail because of the order of char in a sorted list.
from collections import Counter
word = 'ravenous'
candidates = ["raven", "mealwheel", "rasputin"]
def count_fn(mystr):
return sorted(list(Counter(mystr).items()))
def compare_fn (c1,c2):
return ((c1>c2) - (c1<c2))
list_word = count_fn(word)
list_candidates = list(map(count_fn,candidates))
cmp_list = [compare_fn(list_word,i) for i in list_candidates]
cmp_list
#[-1, -1, -1] #should be [1,-1,-1]
So, for below two lists, how can I confirm that list_candidates[0]
is a subset of list_word
. Please note that the comparison ('a',1)
in list_word
against ('a',1)
in list_candidates[i]
could also be ('a',5)
in list_word
against ('a',1)
in list_candidates[i]
; both cases are true.
print(list_word)
#[('a', 1), ('e', 1), ('n', 1), ('o', 1), ('r', 1), ('s', 1), ('u', 1), ('v', 1)]
print(list_candidates[0])
#[('a', 1), ('e', 1), ('n', 1), ('r', 1), ('v', 1)]