First Summer 2006


Lecture Notes Fifteen: Homework six and the the code from the second review session.
  1. (Guess the jumbled word)

    This is what we did first:

    import random
    
    def shuffle(word):
        result = ""
        while len(word) > 0:
            position = random.randrange(len(word))
            result = result + word[position]
            word = word[0:position] + word[position+1:]
        return result
    
    for i in range(10):
        print shuffle("nectarine")
    
    choices = ("one", "three", "nine", "four", "twenty")
    total = 0
    good = 0
    for i in range(4):
        total = total + 1
        word = random.choice(choices)
        guess = raw_input("What word is this: " + shuffle(word) + "? ")
        if guess == word:
            print "Very good."
            good = good + 1
        else:
            print "No, it was least."
        print "So far you got", good, "out of", total

    We decided to clarify one aspect: if the chosen word is "least" then "steal" would not be accepted as a good answer.

  2. (The Fire Extinguisher)

    This is what we did next.

    x = float(raw_input("Percent loss per month: "))
    y = float(raw_input("Percent limit acceptable: "))
    e = 1.0
    count = 0
    LIMIT = 6
    while e >= y and count < LIMIT:
        e = e - x * e
        count = count + 1
        print "After",count,"months extinguisher is at",e,"%"
    print "After",count,"months you need to get a new one"

    This wasn't too bad either.

  3. (Hangman)

    We decided to make it as small as possible:

    import random
    choices = ("house", "nectarine", "chair", "wall", "screen", "trash")
    secret = random.choice(choices)
    mask = "*" * len(secret)
    print "Here's the word:",mask,"(the word really is:",secret,")"
    attempts = 1
    while secret != mask and attempts <= 6:
        letter = raw_input(str(attempts) + ". Guess a letter: ")
        if not letter in secret:
            attempts = attempts + 1
        result = ""
        for i in range(len(secret)):
            if secret[i] == letter:
                result = result + secret[i]
            else:
                result = result + mask[i]
        mask = result
        print mask
    print "Thank you for using this program."

    Notice the game ends after 6 (six) incorrect attempts.

  4. (Count the characters)

    word = raw_input("What's the word: ")
    letter = raw_input("The letter: ")
    count = 0
    for i in range(len(word)):
        print "I am checking word[",i,"]: ",word[i]
        if word[i] == letter:
            count = count + 1
    print letter,"occurs",count,"times in",word

    Notice the loop in this program and in the program before.

We also did the palindrome problem in class.


Last updated: May 30, 2006 by Adrian German for A201/A597