Guest User

ps6

a guest
Jun 6th, 2012
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.72 KB | None | 0 0
  1. # Problem Set 5: 6.00 Word Game
  2. # Name:
  3. # Collaborators:
  4. # Time:
  5. #
  6.  
  7. import random
  8. import string
  9.  
  10. VOWELS = 'aeiou'
  11. CONSONANTS = 'bcdfghjklmnpqrstvwxyz'
  12. HAND_SIZE = 7
  13.  
  14. SCRABBLE_LETTER_VALUES = {
  15. 'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10
  16. }
  17.  
  18. # -----------------------------------
  19. # Helper code
  20. # (you don't need to understand this helper code)
  21.  
  22. WORDLIST_FILENAME = "words.txt"
  23.  
  24. def load_words():
  25. """
  26. Returns a list of valid words. Words are strings of lowercase letters.
  27.  
  28. Depending on the size of the word list, this function may
  29. take a while to finish.
  30. """
  31. print "Loading word list from file..."
  32. # inFile: file
  33. inFile = open(WORDLIST_FILENAME, 'r', 0)
  34. # wordlist: list of strings
  35. word_list = []
  36. for line in inFile:
  37. word_list.append(line.strip().lower())
  38. print " ", len(word_list), "words loaded."
  39. return word_list
  40.  
  41. def get_frequency_dict(sequence):
  42. """
  43. Returns a dictionary where the keys are elements of the sequence
  44. and the values are integer counts, for the number of times that
  45. an element is repeated in the sequence.
  46.  
  47. sequence: string or list
  48. return: dictionary
  49. """
  50. # freqs: dictionary (element_type -> int)
  51. freq = {}
  52. for x in sequence:
  53. freq[x] = freq.get(x,0) + 1
  54. return freq
  55.  
  56.  
  57. # (end of helper code)
  58. # -----------------------------------
  59.  
  60.  
  61. if __name__ == '__main__':
  62. word_list = load_words()
  63. #
  64. # Problem #1: Scoring a word
  65. #
  66. def get_word_score(word, n):
  67.  
  68. score = 0
  69. for letter in word:
  70. score = score + SCRABBLE_LETTER_VALUES[letter]
  71. if len(word) == n:
  72. score = 50+score
  73. return score
  74.  
  75. #
  76. # Make sure you understand how this function works and what it does!
  77. #
  78. def display_hand(hand):
  79.  
  80. for letter in hand.keys():
  81. for j in range(hand[letter]):
  82. print letter,
  83. print
  84.  
  85. def hand_to_list(hand):
  86. hand_list=[]
  87. for letter in hand.keys():
  88. for j in range (hand[letter]):
  89. hand_list.append(letter)
  90. return hand_list
  91.  
  92. def deal_hand(n):
  93.  
  94. hand={}
  95. num_vowels = n / 3
  96.  
  97. for i in range(num_vowels):
  98. x = VOWELS[random.randrange(0,len(VOWELS))]
  99. hand[x] = hand.get(x, 0) + 1
  100.  
  101.  
  102. for i in range(num_vowels, n):
  103. x = CONSONANTS[random.randrange(0,len(CONSONANTS))]
  104. hand[x] = hand.get(x, 0) + 1
  105.  
  106. return hand
  107.  
  108. #
  109. # Problem #2: Update a hand by removing letters
  110. #
  111. def update_hand(hand, word):
  112.  
  113. for letter in word:
  114. hand[letter] -= 1
  115. return hand
  116.  
  117.  
  118.  
  119. def is_valid_word(word,hand,word_list):#in this case you will have to update the hand
  120. #in your play_hand function.
  121. a=0
  122. if word in word_list:
  123. for letter in word:
  124. if letter not in hand:
  125. return False
  126. else:
  127.  
  128. if hand[letter]>=word.count(letter):
  129. a+=1
  130. else:
  131. return False
  132. if a== len(word):
  133. return True
  134. return False
  135.  
  136.  
  137.  
  138.  
  139. def element_counter(hand):
  140. """Counts the number of elements in the hand"""
  141. sum = 0
  142. for i in hand.values():
  143. sum = sum + i
  144. return sum
  145.  
  146. def get_words_to_points(word_list):
  147. """Returns a dict that maps every word in the word_list to its point value"""
  148. word_points = {}
  149. for word in word_list:
  150. points = get_word_score(word,HAND_SIZE)
  151. word_points[word]=points
  152. return word_points
  153.  
  154. points_dict = get_words_to_points(word_list)
  155.  
  156. def pick_best_word(hand,points_dict):
  157. """choses the letters of the hand so as to return the highest scoring word
  158. that can be made from those letters"""
  159. new_dict ={}
  160. for word in points_dict:
  161. validity = is_valid_word(word,hand,points_dict)
  162. if validity:
  163.  
  164. new_dict[word]= points_dict[word]
  165.  
  166.  
  167. max_value = max(new_dict.values())
  168.  
  169. for word in new_dict.keys():
  170. if new_dict[word]== max_value:
  171. return word
  172.  
  173. return "."
  174.  
  175.  
  176.  
  177. def makelistfromhand(hand):#returns list of letters in a hand
  178. new_list=[]
  179. for a in hand.keys():
  180.  
  181. for b in range (0,hand[a]):
  182. new_list.append(a)
  183. return new_list
  184.  
  185.  
  186.  
  187. def subsets(listfromhand):#returns all sub(multi)sets of letters in hand
  188.  
  189. if listfromhand == []:
  190. return [[]]
  191. else:
  192. s = [listfromhand]
  193. for elem in listfromhand:
  194. tmp = listfromhand[:]
  195. tmp.remove(elem)
  196. new_sub = subsets(tmp)
  197. for y in new_sub:
  198. if y not in s:
  199. s.append(y)
  200. return s
  201.  
  202. def stringfromsubsets(listofsubsets): #converts each subset into a sorted string
  203. listofstrings=[]
  204. for i in listofsubsets:
  205. i = sorted(i)
  206. w=""
  207. for j in range(len(i)):
  208. w = w+i[j]
  209. listofstrings.append(w)
  210. return listofstrings
  211.  
  212. def get_word_rearrangements(word_list):
  213. """returns a dict where, for any rearrangement of words in word_list, an
  214. acceptable word from the word_list is returned"""
  215. d = {}
  216. for word in word_list:
  217. sorted_word="".join(sorted(word))
  218. d[sorted_word]= word
  219. return d
  220. rearrange_dict = get_word_rearrangements(word_list)
  221.  
  222.  
  223.  
  224. def pick_best_word_faster(hand):
  225.  
  226. listoflettersinhand = makelistfromhand(hand)
  227. subsetsoflettersinhand = subsets(listoflettersinhand)
  228. sortedstringsubsets = stringfromsubsets(subsetsoflettersinhand)
  229. possiblewordsfromhand ={}
  230. for word in sortedstringsubsets:
  231. if word in rearrange_dict:
  232. possiblewordsfromhand[rearrange_dict[word]]=points_dict[rearrange_dict[word]]
  233. maxkeyvalue= max(possiblewordsfromhand.values())
  234. for word in possiblewordsfromhand:
  235. if possiblewordsfromhand[word]==maxkeyvalue:
  236. return word
  237.  
  238.  
  239. q={'a': 2, 'r': 1, 'e': 2, 't': 1, "s":1}
  240. print "q =", q, "hand size =", element_counter(q)
  241. import time
  242. start = time.time()
  243. pick_best_word_faster(q)
  244. stop = time.time()
  245. duration = stop-start
  246. print "duration for pick_best_word_faster",duration
  247. print pick_best_word_faster(q)
  248. print "q =",q, "hand size =", element_counter(q)
  249. start = time.time()
  250. pick_best_word(q,points_dict)
  251. stop = time.time()
  252. duration = stop-start
  253. print "duration for pick_best_word",duration
  254. print pick_best_word(q,points_dict)
  255.  
  256.  
  257.  
  258. ##import time
  259. ##def get_time_limit(points_dict,k):
  260. ## start_time = time.time()
  261. ## for word in points_dict:
  262. ## get_frequency_dict(word)
  263. ## get_word_score(word,HAND_SIZE)
  264. ## end_time = time.time()
  265. ## return (end_time - start_time)*k
  266. ##
  267. ##time_limit = get_time_limit(points_dict,0.5)
  268. ##
  269. ##import time
  270.  
  271. ##def play_hand(hand, word_list,score = 0,time_limit = time_limit):#my function
  272. ##
  273. ## display_hand(hand)
  274. ## count = element_counter(hand)
  275. ## if count == 0:
  276. ## print "Final Score %0.2f" % score#the %0.2f gives the answer in 2 decimals
  277. ## return None
  278. ## start_time = time.time()
  279. ## word = pick_best_word(hand,points_dict)
  280. ## end_time = time.time()
  281. ## print word
  282. ## duration = end_time- start_time
  283. ## # coz if it's < 1, then while dividing score by duration
  284. ## # the value will be higher than the actual score.
  285. ## print "It took ",duration,"seconds to provide an answer"
  286. ## if time_limit-duration < 0:
  287. ## print "Total time exceeds time limit. You scored %0.2f" % score
  288. ## return None
  289. ## if word == "." :
  290. ## print "Final Score %0.2f" % score
  291. ## return None
  292. ## validity = is_valid_word(word,hand,word_list)
  293. ## if validity == True:
  294. ## time_limit = time_limit-duration
  295. ## print "you have", time_limit,"seconds remaining"
  296. ## word_score = get_word_score(word, HAND_SIZE)
  297. ## if duration <1:
  298. ## word_scoretimed = word_score/1
  299. ## else:
  300. ## word_scoretimed = word_score/duration
  301. ## print "word score timed %0.2f" %word_scoretimed
  302. ## score = score + word_scoretimed
  303. ## print "score so far %0.2f"%score
  304. ## play_hand(update_hand(hand,word),word_list,score,time_limit)
  305. ## if validity == False:
  306. ## print "choose another word"
  307. ## time_limit = time_limit-duration
  308. ## print "you have", time_limit,"seconds remaining"
  309. ## play_hand(hand,word_list,score,time_limit)
  310. ##
  311. ## return None
Advertisement
Add Comment
Please, Sign In to add comment