Guest User

Untitled

a guest
Nov 25th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.73 KB | None | 0 0
  1. # simple python script for cs106b assignment
  2. import subprocess
  3.  
  4. words = list()
  5.  
  6. SYSTEM_DICT_LOOKUP = "egrep -i \"^%s\" /usr/share/dict/words"
  7.  
  8. class Lexicon:
  9. def __init__(self):
  10. self.word_dict = {}
  11.  
  12. def words_for_prefix(self, prefix):
  13. command = SYSTEM_DICT_LOOKUP % (prefix, )
  14.  
  15. try:
  16. result = subprocess.check_output(command, shell=True)
  17. except subprocess.CalledProcessError:
  18. return None
  19.  
  20. wds = result.split("\n")
  21.  
  22. if len(wds) == 0:
  23. return None
  24.  
  25. return wds
  26.  
  27. d_to_l = { "2": "abc" , "3": "def", "4":"ghi", "5":"jkl", "6":"mno", "7":"pqrs", "8":"tuv", "9":"wxyz"}
  28.  
  29. def list_completions(digits, lexicon):
  30. if len(digits) == 1:
  31. # if we only have one digit, just return its possibilities
  32. return list(d_to_l[digits[0]])
  33.  
  34. possibilities = d_to_l[digits[0]]
  35.  
  36. if possibilities is None:
  37. return []
  38.  
  39. possible_pres = list()
  40.  
  41. # we find all possible suffixes of remaining part of the string
  42. possible_suffixes = list_completions(digits[1:], lexicon)
  43.  
  44. # loop through possible first letters
  45. for possibility in possibilities:
  46.  
  47. # try out possible prefixes to other possibilities
  48. for suffix in possible_suffixes:
  49. possible_pres.append(possibility + suffix)
  50.  
  51. return possible_pres
  52.  
  53.  
  54. english = Lexicon()
  55. prefixes = list_completions("72547", english)
  56.  
  57. for prefix in prefixes:
  58. print "Looking up " + prefix + " in dictionary..."
  59.  
  60. ws = english.words_for_prefix(prefix)
  61.  
  62. if ws is not None:
  63. words.extend(ws)
  64.  
  65. print "Prefixes: " + ', '.join(prefixes)
  66.  
  67. print "Words: " + '\n\n-->'.join(words)
Add Comment
Please, Sign In to add comment