Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Problem Set 5: 6.00 Word Game
- # Name:
- # Collaborators:
- # Time:
- #
- import random
- import string
- VOWELS = 'aeiou'
- CONSONANTS = 'bcdfghjklmnpqrstvwxyz'
- HAND_SIZE = 7
- SCRABBLE_LETTER_VALUES = {
- '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
- }
- # -----------------------------------
- # Helper code
- # (you don't need to understand this helper code)
- WORDLIST_FILENAME = "words.txt"
- def load_words():
- """
- Returns a list of valid words. Words are strings of lowercase letters.
- Depending on the size of the word list, this function may
- take a while to finish.
- """
- print "Loading word list from file..."
- # inFile: file
- inFile = open(WORDLIST_FILENAME, 'r', 0)
- # wordlist: list of strings
- word_list = []
- for line in inFile:
- word_list.append(line.strip().lower())
- print " ", len(word_list), "words loaded."
- return word_list
- def get_frequency_dict(sequence):
- """
- Returns a dictionary where the keys are elements of the sequence
- and the values are integer counts, for the number of times that
- an element is repeated in the sequence.
- sequence: string or list
- return: dictionary
- """
- # freqs: dictionary (element_type -> int)
- freq = {}
- for x in sequence:
- freq[x] = freq.get(x,0) + 1
- return freq
- # (end of helper code)
- # -----------------------------------
- if __name__ == '__main__':
- word_list = load_words()
- #
- # Problem #1: Scoring a word
- #
- def get_word_score(word, n):
- score = 0
- for letter in word:
- score = score + SCRABBLE_LETTER_VALUES[letter]
- if len(word) == n:
- score = 50+score
- return score
- #
- # Make sure you understand how this function works and what it does!
- #
- def display_hand(hand):
- for letter in hand.keys():
- for j in range(hand[letter]):
- print letter,
- print
- def hand_to_list(hand):
- hand_list=[]
- for letter in hand.keys():
- for j in range (hand[letter]):
- hand_list.append(letter)
- return hand_list
- def deal_hand(n):
- hand={}
- num_vowels = n / 3
- for i in range(num_vowels):
- x = VOWELS[random.randrange(0,len(VOWELS))]
- hand[x] = hand.get(x, 0) + 1
- for i in range(num_vowels, n):
- x = CONSONANTS[random.randrange(0,len(CONSONANTS))]
- hand[x] = hand.get(x, 0) + 1
- return hand
- #
- # Problem #2: Update a hand by removing letters
- #
- def update_hand(hand, word):
- for letter in word:
- hand[letter] -= 1
- return hand
- def is_valid_word(word,hand,word_list):#in this case you will have to update the hand
- #in your play_hand function.
- a=0
- if word in word_list:
- for letter in word:
- if letter not in hand:
- return False
- else:
- if hand[letter]>=word.count(letter):
- a+=1
- else:
- return False
- if a== len(word):
- return True
- return False
- def element_counter(hand):
- """Counts the number of elements in the hand"""
- sum = 0
- for i in hand.values():
- sum = sum + i
- return sum
- def get_words_to_points(word_list):
- """Returns a dict that maps every word in the word_list to its point value"""
- word_points = {}
- for word in word_list:
- points = get_word_score(word,HAND_SIZE)
- word_points[word]=points
- return word_points
- points_dict = get_words_to_points(word_list)
- def pick_best_word(hand,points_dict):
- """choses the letters of the hand so as to return the highest scoring word
- that can be made from those letters"""
- new_dict ={}
- for word in points_dict:
- validity = is_valid_word(word,hand,points_dict)
- if validity:
- new_dict[word]= points_dict[word]
- max_value = max(new_dict.values())
- for word in new_dict.keys():
- if new_dict[word]== max_value:
- return word
- return "."
- def makelistfromhand(hand):#returns list of letters in a hand
- new_list=[]
- for a in hand.keys():
- for b in range (0,hand[a]):
- new_list.append(a)
- return new_list
- def subsets(listfromhand):#returns all sub(multi)sets of letters in hand
- if listfromhand == []:
- return [[]]
- else:
- s = [listfromhand]
- for elem in listfromhand:
- tmp = listfromhand[:]
- tmp.remove(elem)
- new_sub = subsets(tmp)
- for y in new_sub:
- if y not in s:
- s.append(y)
- return s
- def stringfromsubsets(listofsubsets): #converts each subset into a sorted string
- listofstrings=[]
- for i in listofsubsets:
- i = sorted(i)
- w=""
- for j in range(len(i)):
- w = w+i[j]
- listofstrings.append(w)
- return listofstrings
- def get_word_rearrangements(word_list):
- """returns a dict where, for any rearrangement of words in word_list, an
- acceptable word from the word_list is returned"""
- d = {}
- for word in word_list:
- sorted_word="".join(sorted(word))
- d[sorted_word]= word
- return d
- rearrange_dict = get_word_rearrangements(word_list)
- def pick_best_word_faster(hand):
- listoflettersinhand = makelistfromhand(hand)
- subsetsoflettersinhand = subsets(listoflettersinhand)
- sortedstringsubsets = stringfromsubsets(subsetsoflettersinhand)
- possiblewordsfromhand ={}
- for word in sortedstringsubsets:
- if word in rearrange_dict:
- possiblewordsfromhand[rearrange_dict[word]]=points_dict[rearrange_dict[word]]
- maxkeyvalue= max(possiblewordsfromhand.values())
- for word in possiblewordsfromhand:
- if possiblewordsfromhand[word]==maxkeyvalue:
- return word
- q={'a': 2, 'r': 1, 'e': 2, 't': 1, "s":1}
- print "q =", q, "hand size =", element_counter(q)
- import time
- start = time.time()
- pick_best_word_faster(q)
- stop = time.time()
- duration = stop-start
- print "duration for pick_best_word_faster",duration
- print pick_best_word_faster(q)
- print "q =",q, "hand size =", element_counter(q)
- start = time.time()
- pick_best_word(q,points_dict)
- stop = time.time()
- duration = stop-start
- print "duration for pick_best_word",duration
- print pick_best_word(q,points_dict)
- ##import time
- ##def get_time_limit(points_dict,k):
- ## start_time = time.time()
- ## for word in points_dict:
- ## get_frequency_dict(word)
- ## get_word_score(word,HAND_SIZE)
- ## end_time = time.time()
- ## return (end_time - start_time)*k
- ##
- ##time_limit = get_time_limit(points_dict,0.5)
- ##
- ##import time
- ##def play_hand(hand, word_list,score = 0,time_limit = time_limit):#my function
- ##
- ## display_hand(hand)
- ## count = element_counter(hand)
- ## if count == 0:
- ## print "Final Score %0.2f" % score#the %0.2f gives the answer in 2 decimals
- ## return None
- ## start_time = time.time()
- ## word = pick_best_word(hand,points_dict)
- ## end_time = time.time()
- ## print word
- ## duration = end_time- start_time
- ## # coz if it's < 1, then while dividing score by duration
- ## # the value will be higher than the actual score.
- ## print "It took ",duration,"seconds to provide an answer"
- ## if time_limit-duration < 0:
- ## print "Total time exceeds time limit. You scored %0.2f" % score
- ## return None
- ## if word == "." :
- ## print "Final Score %0.2f" % score
- ## return None
- ## validity = is_valid_word(word,hand,word_list)
- ## if validity == True:
- ## time_limit = time_limit-duration
- ## print "you have", time_limit,"seconds remaining"
- ## word_score = get_word_score(word, HAND_SIZE)
- ## if duration <1:
- ## word_scoretimed = word_score/1
- ## else:
- ## word_scoretimed = word_score/duration
- ## print "word score timed %0.2f" %word_scoretimed
- ## score = score + word_scoretimed
- ## print "score so far %0.2f"%score
- ## play_hand(update_hand(hand,word),word_list,score,time_limit)
- ## if validity == False:
- ## print "choose another word"
- ## time_limit = time_limit-duration
- ## print "you have", time_limit,"seconds remaining"
- ## play_hand(hand,word_list,score,time_limit)
- ##
- ## return None
Advertisement
Add Comment
Please, Sign In to add comment