Thursday, July 21, 2011

MIT 6.00 Problem Set 6 Answer - Problems 1 & 2


Python Code Answer:

def play_hand(hand, word_list):
    total_score = 0.0
    min_elapsed = 0.010
    hand_score = 0.0

    time_limit = raw_input('Enter Time Limit: ')
    
    if time_limit.isdigit():
        time_limit = float(time_limit)
    else:
        print "Enter Valid Time Limit"
        return

    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

        start = time.time()
        word = raw_input('Word: ')
        stop = time.time()
        
        elapsed = stop - start
        time_limit -= elapsed

        # prevent divide by zero error, force min time
        if elapsed < min_elapsed:
            elapsed = min_elapsed

        if word == '.':
            break

        if is_valid_word(word, hand, word_list):
            update_hand(hand, word)
            if time_limit > 0.0:
                hand_score = get_word_score(word, num_letters) / elapsed
                total_score += hand_score
            else:
                print "Time limit exceeded."
            print "Score: %0.2f  Total Score: %0.2f" % (hand_score, total_score)
        else:
            print "Invalid word. Try again."

        if time_limit >= 0:
            print "Turn took %0.2f seconds, %0.2f seconds remaining" % (elapsed, time_limit)
    
    print "Final Score: %0.2f" % (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
Enter Time Limit: 10

q e t h j o n Word: note
Score: 0.44  Total Score: 0.44
Turn took 9.05 seconds, 0.95 seconds remaining

q h j Word: .
Final Score: 0.44

Enter n to deal a new hand, r to replay the last hand, or e to end game:
Invalid command.
Enter n to deal a new hand, r to replay the last hand, or e to end game: n
Enter Time Limit:
Enter Valid Time Limit

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

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

a q v p j j o Word:
Invalid word. Try again.

a q v p j j o Word: .
Final Score: 0.00

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

p u t i h z n Word: putz
Score: 3.28  Total Score: 3.28
Turn took 4.57 seconds, 5.43 seconds remaining

i h n Word: hin
Score: 1.51  Total Score: 4.79
Turn took 3.98 seconds, 1.45 seconds remaining

Final Score: 4.79

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


No comments:

Post a Comment