Advertisement
Guest User

NPR Puzzle: Trees to Herbs and Spices in Python

a guest
Aug 13th, 2014
353
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.72 KB | None | 0 0
  1. from nltk.corpus import wordnet as wn
  2.  
  3. def get_category_members(name):
  4.     '''
  5.    Use NLTK to get members of a category
  6.    
  7.    Huge thanks to http://stackoverflow.com/questions/15330725/how-to-get-all-the-hyponyms-of-a-word-synset-in-python-nltk-and-wordnet
  8.    '''
  9.     members = set()
  10.     synsets = wn.synsets(name)
  11.     for synset in synsets:
  12.         members = members.union(set([w for s in synset.closure(lambda s:s.hyponyms(),depth=10) for w in s.lemma_names]))
  13.     return members
  14.  
  15. def w1_in_w2(w1,w2):
  16.     '''
  17.    Return leftover letters if all the letters from w1 are in w2
  18.    Return False otherwise
  19.    '''
  20.     for c in w1:
  21.         if c not in w2:
  22.             return False
  23.         else:
  24.             pos = w2.find(c)
  25.             w2 = w2[:pos] + w2[pos+1:]
  26.     return w2
  27.  
  28.  
  29. # Set of trees
  30. trees = frozenset(get_category_members('tree'))
  31.  
  32. # Set of herbs and spices
  33. herbs_spices = set()
  34. for x in ('herb','spice'):
  35.     herbs_spices = herbs_spices.union(get_category_members(x))
  36. # Dictionary to help find anagrams
  37. sorted_to_word = dict()
  38. for word in herbs_spices:
  39.     word = word.lower()
  40.     s = ''.join(sorted(word))
  41.     try:
  42.         sorted_to_word[s].append(word)
  43.     except KeyError:
  44.         sorted_to_word[s] = [word]
  45.  
  46. # Go through and give results
  47. for tree in trees:
  48.     for herb in herbs_spices:
  49.         leftover = w1_in_w2(herb.lower(),tree.lower())
  50.         if leftover:
  51.             l = leftover.replace('_','')
  52.             s = ''.join(sorted(l))    
  53.             try:
  54.                 new_words = sorted_to_word[s]
  55.             except KeyError:
  56.                 new_words = []
  57.             for spice in new_words:
  58.                 print "%s -> %s %s" % (tree, herb, spice)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement