A201

Assignment 8

Hangman

Individual work on this lab and assignment.

Complete the functions below.

In Lab

def area_code(phone_number):
    """
    Assuming phone_number is a string of the form [ddd]ddd-dddd, return
    the area code digits as a string.

    >>> area_code('[812]855-3376')
    '812'
    >>>
    """
    # Hint: use slicing
    #...

def phone_number_to_integer(phone_number):
    """
    Assuming phone_number is a string of the form [ddd]ddd-dddd, return
    the number as a (long) integer.
    
    >>> phone_number_to_integer('[812]855-3376')
    8128553376L
    >>>
    """
    # Hint: the int function will create a long integer given a string
    # representing an integer with 10 digits.
    #.
    #.

def is_hex(string):
    """
    Returns true if the string contains only hexidecimal digits (0-9 and a-f,
    case-insensitive).
    
    >>> is_hex('3F2a')
    True
    >>> is_hex('2J')
    False
    >>> 
    """
    # Hint: use the in operator
    hex_digits = '0123456789ABCDEFabcdef'
    #...
    while index < len(string):
        if not string[index] in hex_digits:
    #.
    #.
    #.

def find(string, substring):
    """
    If string contains the given substring, return the lowest index in
    string where the substring begins. Return -1 if the substring is not 
    found in the string.
    
    >>> find('say it again and again', 'again')
    7
    >>> find('not again', 'nope')
    -1
    >>>
    """
    # FYI: this is similar to the string method find(substring), and 
    # a more general version of the find function in chapter 7 of the text.
    #
    # Hint: use a while loop with an index variable to compare slices of
    # string with the substring.
    #.
    #.
    #.
    #.
    #.
    #.
    #.

def space_separate(s):
    """
    Return a copy of string s with a space inserted between each of the
    characters of string s.
    
    >>> space_separate('abc')
    'a b c'
    >>> space_separate('')
    ''
    >>>
    """
    # Hint: use iteration over the characters of s
    #.
    #.
    #.
    #.
    #.
    #.

def shuffle(s1, s2):
    """Return the perfect shuffle of strings s1 and s2, starting with s1. That
    is, return a string that alternates the characters of s1 and s2, starting
    with the first character of s1. If one string is shorter, the extra
    characters of the longer one are appended to the result.

    >>> shuffle('abc', 'def')
    'adbecf'
    >>> shuffle('abc', 'd')
    'adbc'
    >>> shuffle('', 'a')
    'a'
    >>>
    """
    #...
    #...
    while i < len(s1) and i < len(s2):
        #...
        #...
    if i < len(s1):
    #.
    #.
    #.
    #.

def reverse(s):
    """
    Return a string with the characters of string s in reverse order.
    
    >>> reverse('abc')
    'cba'
    >>> reverse('')
    ''
    >>>
    """
    # Hint: implement with an indexing, accumulating while loop, that
    # decrements the index.
    #...
    index = len(s) - 1
    while index >= 0:
    #.
    #.
    #.

def main():
    """In this function add a few tests for each function in the file."""

main()

Before the lab is over submit your lab8.txt file via Oncourse and be sure you understand the assignment.

Assignment

Due 3pm, March 6th
# a8.py, <YOUR NAME, USERNAME, AND LAB TIME HERE>
import random

WORDS = ''' able about account acid across act addition adjustment advertisement after
again against agreement air all almost among amount amusement and angle
angry animal answer ant any apparatus apple approval arch argument arm army
art as at attack attempt attention attraction authority automatic awake
baby back bad bag balance ball band base basin basket bath be beautiful
because bed bee before behaviour belief bell bent berry between bird birth
bit bite bitter black blade blood blow blue board boat body boiling bone
book boot bottle box boy brain brake branch brass bread breath brick bridge
bright broken brother brown brush bucket building bulb burn burst business
but butter button by cake camera canvas card care carriage cart cat cause
certain chain chalk chance change cheap cheese chemical chest chief chin
church circle clean clear clock cloth cloud coal coat cold collar colour
comb come comfort committee common company comparison competition complete
complex condition connection conscious control cook copper copy cord cork
cotton cough country cover cow crack credit crime cruel crush cry cup cup
current curtain curve cushion damage danger dark daughter day dead dear
death debt decision deep degree delicate dependent design desire
destruction detail development different digestion direction dirty
discovery discussion disease disgust distance distribution division do dog
door doubt down drain drawer dress drink driving drop dry dust ear early
earth east edge education effect egg elastic electric end engine enough
equal error even event ever every example exchange existence expansion
experience expert eye face fact fall false family far farm fat father fear
feather feeble feeling female fertile fiction field fight finger fire first
fish fixed flag flame flat flight floor flower fly fold food foolish foot
for force fork form forward fowl frame free frequent friend from front
fruit full future garden general get girl give glass glove go goat gold
good government grain grass great green grey grip group growth guide gun
hair hammer hand hanging happy harbour hard harmony hat hate have he head
healthy hear hearing heart heat help high history hole hollow hook hope
horn horse hospital hour house how humour I ice idea if ill important
impulse in increase industry ink insect instrument insurance interest
invention iron island jelly jewel join journey judge jump keep kettle key
kick kind kiss knee knife knot knowledge land language last late laugh law
lead leaf learning leather left leg let letter level library lift light
like limit line linen lip liquid list little living lock long look loose
loss loud love low machine make male man manager map mark market married
mass match material may meal measure meat medical meeting memory metal
middle military milk mind mine minute mist mixed money monkey month moon
morning mother motion mountain mouth move much muscle music nail name
narrow nation natural near necessary neck need needle nerve net new news
night no noise normal north nose not note now number nut observation of off
offer office oil old on only open operation opinion opposite or orange
order organization ornament other out oven over owner page pain paint paper
parallel parcel part past paste payment peace pen pencil person physical
picture pig pin pipe place plane plant plate play please pleasure plough
pocket point poison polish political poor porter position possible pot
potato powder power present price print prison private probable process
produce profit property prose protest public pull pump punishment purpose
push put quality question quick quiet quite rail rain range rat rate ray
reaction reading ready reason receipt record red regret regular relation
religion representative request respect responsible rest reward rhythm rice
right ring river road rod roll roof room root rough round rub rule run sad
safe sail salt same sand say scale school science scissors screw sea seat
second secret secretary see seed seem selection self send sense separate
serious servant sex shade shake shame sharp sheep shelf ship shirt shock
shoe short shut side sign silk silver simple sister size skin  skirt sky
sleep slip slope slow small smash smell smile smoke smooth snake sneeze
snow so soap society sock soft solid some  son song sort sound soup south
space spade special sponge spoon spring square stage stamp star start
statement station steam steel stem step stick sticky stiff still stitch
stocking stomach stone stop store story straight strange street stretch
strong structure substance such sudden sugar suggestion summer sun support
surprise sweet swim system table tail take talk tall taste tax teaching
tendency test than that the then theory there thick thin thing this thought
thread throat through through thumb thunder ticket tight till time tin
tired to toe together tomorrow tongue tooth top touch town trade train
transport tray tree trick trouble trousers true turn twist umbrella under
unit up use value verse very vessel view violent voice waiting walk wall
war warm wash waste watch water wave wax way weather week weight well west
wet wheel when where while whip whistle white who why wide will wind window
wine wing winter wire wise with woman wood wool word work worm wound
writing wrong year yellow yes yesterday you young '''

def replace_char(s, old, new):
    """
    Return the result of replaceing all occurrences of character old
    with character new in string s.
    
    >>> replace_char('You DID!', 'D', 'x')
    'You xIx!'
    >>>
    """
    # Hint: use an indexed accumulating loop
    #...
    #...
    while index < len(s):
        if s[index] == old: 
    #.
    #.
    #.
    #.
    #.

def count_chars(s, c):
    """
    Return the number of occurrences of character c in string s.
    
    >>> count_chars('Yes I did!', 'd')
    2
    >>> count_chars('Yes I did!', '!')
    1
    >>> count_chars('Yes I did!', 'x')
    0
    >>>
    """
    # Hint: use an indexed accumulating loop
    #.
    #.
    #.
    #.
    #.
    #.
    #.

def find_nth_char(s, c, n):
    """
    Return the index of the nth occurrence in string s of character c,
    or -1 if there are not n occurrences in s of the characters in chars.

    >>> find_nth_char('You did just then!', 'd', 1)
    4
    >>> find_nth_char('You did just then!', 'd', 2)
    6
    >>> find_nth_char('You did just then!', 'o', 3)
    -1
    >>>
    """
    # Hint: use an indexed loop
    #.
    #.
    #.
    #.
    #.
    #.
    #.
    #.
    #.

def nth_word(words, n):
    """
    Return the nth word in the given string of space-separated words,
    or None if there are fewer than n words. Assume words starts and
    ends with a space.
    
    >>> nth_word(' You most certainly did not! ', 1)
    'You'
    >>> nth_word(' You most certainly did not! ', 5)
    'not!'
    >>> nth_word(' You most certainly did not! ', 6)
    >>> # None returned
    """
    # Hint: use find_nth_char (twice) and slicing. A loop is not needed.
    begin = find_nth_char(words, ' ', n) + 1
    #...
    if end == -1:
        return None
    #.
    #.

def random_word():
    """
    Return a word chosen randomly from WORDS, a string of space and newline
    separated words, beginning and ending with a space.
    """
    # Hint: use replace_char to replace newlines by spaces, count_chars to
    # determine the number of words, and finally nth_word and random.randrange.
    #.
    #.
    #.

def make_template(s, chars):
    """
    Return s with characters not in chars replaced by an underscore.

    >>> make_template('spamalot', 'aso')
    's_a_a_o_'
    >>>
    """
    #...
    #...
    while index < len(s):
        if s[index] in chars:
    #.
    #.
    #.
    #.
    #.

def hangman():
    """
    The computer randomly chooses a word and the user tries to guess the
    characters in the word.

    At each turn the word is displayed with each character not guessed so
    far replaced by an underscore, along with the misses (guessed
    characters that are not in the word). The user is then prompted to
    guess a character.

    When all the characters have been guessed the word and the number of misses
    are printed and the game ends.  The lower the number of misses the better
    the play.

    If nothing is entered, the word is printed and the game end, and if
    more than one character is enterred, the entry is silently ignored.

    This is essentially the hangman word game, without any nasty hanging.

    Two short game transcripts follow:
        
        Guess a character (or nothing to quit): a
        word: _____  misses: a
        Guess a character (or nothing to quit): e
        word: e____  misses: a
        Guess a character (or nothing to quit): i
        word: e____  misses: ai
        Guess a character (or nothing to quit): r
        word: err_r  misses: ai
        Guess a character (or nothing to quit): o
        You got the word error with 2 misses

        Guess a character (or nothing to quit): e
        word: e__  misses: 
        Guess a character (or nothing to quit): a
        word: e__  misses: a
        Guess a character (or nothing to quit): 
        You didn't guess the word egg
    """
    word = random_word()
    guessed = '' # characters guessed correctly
    misses = '' # characters guessed incorrectly
    while True:
        template = make_template(word, guessed)
    #.
    #.
    #.
    #.
    #.
    #.
    #.
    #.
    #.
    #.
    #.
    #.
    #.

def main():
    """In this function add a few tests for each function in the file."""
    hangman()

main()

All the functions in this assignment are used in the hangman game when it is implemented as intended.

All the functions besides make_template and hangman are used only to picking a random word from the given string of 849 words.

If you can't get some of these functions to work, modify your program so it does not depend on them.

  • replace_char is only needed if the words string contains multiple lines.
  • count_chars is not needed if you code the number of words in the word list as a constant.
  • find_nth_char and nth_word are not needed if you modify the game to prompt for a word at the beginning (presuming the word is entered by someone else while the player isn't looking).

Submit your work via Oncourse as usual.