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


2 comments:

  1. M Resort Casino, Tropicana, FL - TripAdvisor
    M Resort Casino, Tropicana, FL: Find reviews and discounts for AAA/AARP members, seniors, long stays & government.Room types: Non-smoking roomsSuitesSmokiProperty amenities: Free parkingFree High SpRoom 거제 출장안마 features: Air conditioningPrivate balcon Rating: 4 · ‎19 reviews · ‎Price range: 김제 출장샵 $ (Based on Average Nightly Rates 거제 출장안마 for a Standard Room 양산 출장마사지 from our Partners)Which popular attractions are close to M Resort Casino?What are some of the property 당진 출장샵 amenities at M Resort Casino?

    ReplyDelete