0

Doing the CS101 course for the github OSS and I've got a bug with one of the projects where generally it runs fine but with a specific use case(input: o, m, n, ., n) that last 'n' triggers the Else block (even though it prints out 'n' for the variable gameDecision. I've tried everything I can think of but am coming up short. Since the course is closed, any advice would be greatly appreciated. Thanks!

Link to problem: https://courses.edx.org/courses/course-v1:MITx+6.00.1x_8+1T2016/courseware/Week_4/Problem_Set_4/

Code:

# 6.00x Problem Set 4A Template
#
# The 6.00 Word Game
# Created by: Kevin Luu <luuk> and Jenna Wiens <jwiens>
# Modified by: Sarina Canelake <sarina>
#

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 loadWords():
    """
    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
    wordList = []
    for line in inFile:
        wordList.append(line.strip().lower())
    print "  ", len(wordList), "words loaded."
    return wordList

def getFrequencyDict(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)
# -----------------------------------

#
# Problem #1: Scoring a word
#
def getWordScore(word, n):
    """
    Returns the score for a word. Assumes the word is a valid word.

    The score for a word is the sum of the points for letters in the
    word, multiplied by the length of the word, PLUS 50 points if all n
    letters are used on the first turn.

    Letters are scored as in Scrabble; A is worth 1, B is worth 3, C is
    worth 3, D is worth 2, E is worth 1, and so on (see SCRABBLE_LETTER_VALUES)

    word: string (lowercase letters)
    n: integer (HAND_SIZE; i.e., hand size required for additional points)
    returns: int >= 0
    """
    # TO DO ... <-- Remove this comment when you code this function
    count = 0
    for i in word:
        count += SCRABBLE_LETTER_VALUES[i]
    count *= len(word)
    if len(word) == n:
        count += 50
    return count



#
# Problem #2: Make sure you understand how this function works and what it does!
#
def displayHand(hand):
    """
    Displays the letters currently in the hand.

    For example:
    >>> displayHand({'a':1, 'x':2, 'l':3, 'e':1})
    Should print out something like:
       a x x l l l e
    The order of the letters is unimportant.

    hand: dictionary (string -> int)
    """
    for letter in hand.keys():
        for j in range(hand[letter]):
             print letter,              # print all on the same line
    print                               # print an empty line

#
# Problem #2: Make sure you understand how this function works and what it does!
#
def dealHand(n):
    """
    Returns a random hand containing n lowercase letters.
    At least n/3 the letters in the hand should be VOWELS.

    Hands are represented as dictionaries. The keys are
    letters and the values are the number of times the
    particular letter is repeated in that hand.

    n: int >= 0
    returns: dictionary (string -> int)
    """
    hand={}
    numVowels = n / 3

    for i in range(numVowels):
        x = VOWELS[random.randrange(0,len(VOWELS))]
        hand[x] = hand.get(x, 0) + 1

    for i in range(numVowels, 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 updateHand(hand, word):
    """
    Assumes that 'hand' has all the letters in word.
    In other words, this assumes that however many times
    a letter appears in 'word', 'hand' has at least as
    many of that letter in it. 

    Updates the hand: uses up the letters in the given word
    and returns the new hand, without those letters in it.

    Has no side effects: does not modify hand.

    word: string
    hand: dictionary (string -> int)    
    returns: dictionary (string -> int)
    """
    # TO DO ... <-- Remove this comment when you code this function
    chand = hand.copy()
    for i in word:
        if chand.get(i,0) == 0:
            return False
            break
        else:
            chand[i] -= 1
    return chand    


#
# Problem #3: Test word validity
#
def isValidWord(word, hand, wordList):
    """
    Returns True if word is in the wordList and is entirely
    composed of letters in the hand. Otherwise, returns False.

    Does not mutate hand or wordList.

    word: string
    hand: dictionary (string -> int)
    wordList: list of lowercase strings
    """
    # TO DO ... <-- Remove this comment when you code this function
    chand = hand.copy()
    if word in wordList and updateHand(chand, word) != False:
        return True
    else:
        return False


#
# Problem #4: Playing a hand
#

def calculateHandlen(hand):
    """ 
    Returns the length (number of letters) in the current hand.

    hand: dictionary (string-> int)
    returns: integer
    """
    # TO DO... <-- Remove this comment when you code this function
    length = 0
    for i in hand:
        length += hand.get(i, 0)
    return length




def playHand(hand, wordList, n):
    """
    Allows the user to play the given hand, as follows:

    * The hand is displayed.
    * The user may input a word or a single period (the string ".") 
      to indicate they're done playing
    * Invalid words are rejected, and a message is displayed asking
      the user to choose another word until they enter a valid word or "."
    * When a valid word is entered, it uses up letters from the hand.
    * After every valid word: the score for that word is displayed,
      the remaining letters in the hand are displayed, and the user
      is asked to input another word.
    * The sum of the word scores is displayed when the hand finishes.
    * The hand finishes when there are no more unused letters or the user
      inputs a "."

      hand: dictionary (string -> int)
      wordList: list of lowercase strings
      n: integer (HAND_SIZE; i.e., hand size required for additional points)

    """
    score = 0

    while calculateHandlen(hand) > 0:

        displayHand(hand)
        word = raw_input("Please provide a word: ")
        if word == ".":
            break
        else:
            if isValidWord(word, hand, wordList) != True:
                print "Please enter a valid word"

            else:
                print "Points scored: " + str(getWordScore(word, n))
                score += getWordScore(word, n)
                hand = updateHand(hand,word)

    print "Game over! Total score: " + str(score)


#
# Problem #5: Playing a game
# 

def playGame(wordList):
    """
    Allow the user to play an arbitrary number of hands.

    1) Asks the user to input 'n' or 'r' or 'e'.
      * If the user inputs 'n', let the user play a new (random) hand.
      * If the user inputs 'r', let the user play the last hand again.
      * If the user inputs 'e', exit the game.
      * If the user inputs anything else, tell them their input was invalid.

    2) When done playing the hand, repeat from step 1    
    """

    n = random.randint(3,9)
    hand = dealHand(n)
    gameDecision = raw_input("Input 'n' or 'r' or 'e': ")
    quitting = False


    while quitting == False:

        if gameDecision == "n":
            n = random.randint(3,9)
            hand = dealHand(n)
            playHand(hand, wordList, n)
            gameDecision = raw_input("Input 'n' or 'r' or 'e': ")

        if gameDecision == "r":
            playHand(hand, wordList, n)
            gameDecision = raw_input("Input 'n' or 'r' or 'e': ")

        if gameDecision == "e":
            quitting = True

        else:
            print "Input is invalid"
            gameDecision = raw_input("Input 'n' or 'r' or 'e': ")               

#
# Build data structures used for entire session and play game
#
if __name__ == '__main__':
    wordList = loadWords()
    playGame(wordList)
2
  • 1
    I think you want to be using 'elif' instead of 'if' for the r and e case. Commented Apr 21, 2016 at 22:52
  • Also, this question is severely lacking a MCVE Commented Apr 21, 2016 at 22:53

1 Answer 1

2

Because of the way you formed this block:

    if gameDecision == "n":
        n = random.randint(3,9)
        hand = dealHand(n)
        playHand(hand, wordList, n)
        gameDecision = raw_input("Input 'n' or 'r' or 'e': ")

    if gameDecision == "r":
        playHand(hand, wordList, n)
        gameDecision = raw_input("Input 'n' or 'r' or 'e': ")

    if gameDecision == "e":
        quitting = True

    else:
        print "Input is invalid"
        gameDecision = raw_input("Input 'n' or 'r' or 'e': ")       

The else case is tied to the if case for the "e" character. You should be using "elif" statements for the "r" and "e" case.

Sign up to request clarification or add additional context in comments.

1 Comment

thank you I knew it would be something simple and stupid!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.