Monday, July 18, 2011

MIT 6.00 Problem Set 5 - Problems 1 - 4 Answers

Juvenile Gull, Australia
Problem set 5 has a framework of provided code to complete the assignment within. Below is the code that needs to be added to the framework to complete the assignment.

Python Code Answer:

# Problem #1: Scoring a word
def get_word_score(word, n):
    score = 0

    for c in word:
        score += SCRABBLE_LETTER_VALUES[c]

    if len(word) == HAND_SIZE:
        score += 50

    return score



# Problem #2: Update a hand by removing letters

def update_hand(hand, word):
    for c in word:
        hand[c] -= 1

    return hand


# Problem #3: Test word validity
def is_valid_word(word, hand, word_list):
    local_hand = hand.copy()

    for c in word:
        if local_hand.get(c, 0) == 0:
            return False
        else:
            local_hand[c] -= 1
    
    if word.lower() in word_list:
        return True
    else:
        return False
            

# Problem #4: Playing a hand
def play_hand(hand, word_list):
    total_score = 0

    while True:        
        print

        num_letters = 0
        for key in hand.keys():
            for i in range(hand[key]):
                num_letters += 1
                print key,

        if num_letters < 1:
            break

        word = raw_input('Word: ')

        if word == '.':
            break

        if is_valid_word(word, hand, word_list):
            update_hand(hand, word)
            hand_score = get_word_score(word, num_letters)
            total_score += hand_score
            print "Score: %d  Total Score: %d" % (hand_score, total_score)
        else:
            print "Invalid word. Try again."
    
    print "Final Score: %d" % (total_score)

Output:

Loading word list from file...
   83667 words loaded.
Enter n to deal a new hand, r to replay the last hand, or e to end game: n

u y h j o n n Word: joy
Score: 13  Total Score: 13

u h n n Word: hun
Score: 6  Total Score: 19

n Word: .
Final Score: 19

Enter n to deal a new hand, r to replay the last hand, or e to end game: n

r r u v k l o Word: .
Final Score: 0

Enter n to deal a new hand, r to replay the last hand, or e to end game: n

a r u w y h j Word: yaw
Score: 9  Total Score: 9

r u h j Word: .
Final Score: 9


No comments:

Post a Comment