Saturday, September 28, 2013

Learn to Program: The Fundamentals - Assignment 3

Preface

No printing!

Don't call print anywhere in your code. By now, you should be using the visualizer or the debugger to figure out what your code is doing.

A3 Problem Domain: Word Search Game

For A3, you will implement a word search game. The game involves an rectangular board of uppercase letters that is read from a file. For example, here are the file contents representing a (tiny) 2 row by 4 column board: 

ANTT
XSOB

The game also involves a non-empty words list read from a file. For example, here are example file contents for a words list:
ANT
BOX
SOB
TO
 
To make it a bit more challenging, there may be words in the words list that do not appear in the board, and the word list is not shown to the players.
The object of the game is for the players to view the board and find words (remember that the words list is unknown to the players). Words may be contained in rows (from left to right) or columns (from top to bottom), but not backwards. When a player correctly guesses a word that occurs in the words list, that player is awarded points according to a scoring system described in the starter code. The game ends when all words on the board that appear in the words list have been guessed.
The player with the highest score wins.
The words from the words list and the letters of the board are made up of alphabetic, uppercase characters.

Terminology in this handout

  • A board is a list of list of str, such as [['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']].
  • A words list is a list of str such as ['ANT', 'BOX', 'SOB', 'TO']



It will be useful to call some of these functions when implementing other functions. Here is some information about how the functions relate to each other and how they are used in the game:
  • is_valid_word: checks whether a word that player guessed is in the words list.
  • make_str_from_row: creates a string from the list of single character strings representing a row. Hint: look at how this is used by board_contains_word_in_row.
  • make_str_from_column: creates a string from the list of single character strings representing a column. Hint: this may be helpful for board_contains_word_in_column.
  • board_contains_word_in_row: checks whether a word occurs in any of the rows of the board. This function has been implemented in the starter code.
  • board_contains_word_in_column: checks whether a word occurs in any of the columns of the board. Hint: see board_contains_word_in_row.
  • board_contains_word: checks whether a word occurs in any of the rows or columns of the board.
  • word_score: calculates the score that a correctly guessed word earns. A word that is only 1 or 2 letters long earns 0 points, a word that is 3-6 letters long earns 1 point per letter, a word that is 7-9 letters long earns 2 points per letter, and a word that is 10 or more letters long earns 3 points per letter.
  • update_score: adds the score that a correctly guessed word earns to a player's score.
  • num_words_on_board: counts how many words from the words list appear on a particular board.
  • read_words: creates a words list made up of the words from a file. Hint: to test this function, you should open a file such as wordslist1.txt and pass the open file as an argument to this function. 
  • read_board: creates a board made up of the rows of letters from a file. Hint: to test this function, you should open a file such as board1.txt and pass the open file as an argument to this function. 
"""A board is a list of list of str. For example, the board
    ANTT
    XSOB
is represented as the list
    [['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']]

A word list is a list of str. For example, the list of words
    ANT
    BOX
    SOB
    TO
is represented as the list
    ['ANT', 'BOX', 'SOB', 'TO']
"""


def is_valid_word(wordlist, word):
    """ (list of str, str) -> bool

    Return True if and only if word is an element of wordlist.

    >>> is_valid_word(['ANT', 'BOX', 'SOB', 'TO'], 'TO')
    True
    """
   
    i = 0
    while i < len(wordlist):
        return word in wordlist
        i = i + 1


def make_str_from_row(board, row_index):
    """ (list of list of str, int) -> str

    Return the characters from the row of the board with index row_index
    as a single string.

    >>> make_str_from_row([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 0)
    'ANTT'
    """

    word = ''
    i = row_index
    for char in board[i]:
        word = word + char
    return word


def make_str_from_column(board, column_index):
    """ (list of list of str, int) -> str

    Return the characters from the column of the board with index column_index
    as a single string.

    >>> make_str_from_column([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 1)
    'NS'
    """

    word = ''
    i = column_index
    for char in board:
        word =  word + (char[i])
    return word


def board_contains_word_in_row(board, word):
    """ (list of list of str, str) -> bool
    Return True if and only if one or more of the rows of the board contains word.

    Precondition: board has at least one row and one column, and word is a valid word.

    >>> board_contains_word_in_row([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 'SOB')
    True
    """

    for row_index in range(len(board)):
        if word in make_str_from_row(board, row_index):
            return True

    return False


def board_contains_word_in_column(board, word):
    """ (list of list of str, str) -> bool

    Return True if and only if one or more of the columns of the board contains word.

    Precondition: board has at least one row and one column, and word is a valid word.

    >>> board_contains_word_in_column([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 'NO')
    False
    """

    i = 0
    while i < len(board[0]):
        if word in make_str_from_column(board, i):
            return True
        i = i + 1
       
    return False


def board_contains_word(board, word):
    """ (list of list of str, str) -> bool

    Return True if and only if word appears in board.

    Precondition: board has at least one row and one column.

    >>> board_contains_word([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], 'ANT')
    True
    """

    a = board_contains_word_in_row(board, word)
    b = board_contains_word_in_column(board, word)
    if a or b:
        return True
    return False


def word_score(word):
    """ (str) -> int

    Return the point value the word earns.

    Word length: < 3: 0 points
                 3-6: 1 point per character for all characters in word
                 7-9: 2 points per character for all characters in word
                 10+: 3 points per character for all characters in word

    >>> word_score('DRUDGERY')
    16
    """

    score = len(word)
    if score < 3:
        return score*0
    elif score >=3 and score <=6:
        return score*1
    elif score >=7 and score <=9:
        return score*2
    elif score >=10:
        return score*3
    return score


def update_score(player_info, word):
    """ ([str, int] list, str) -> NoneType

    player_info is a list with the player's name and score. Update player_info
    by adding the point value word earns to the player's score.

    >>> update_score(['Jonathan', 4], 'ANT')
    """

    current_point = player_info.pop(1)
    point = current_point + word_score(word)
    player_info.append(point)

   

def num_words_on_board(board, words):
    """ (list of list of str, list of str) -> int

    Return how many words appear on board.

    >>> num_words_on_board([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], ['ANT', 'BOX', 'SOB', 'TO'])
    3
    """

    count = 0
    for word in words:
        if board_contains_word(board, word):
            count = count + 1
    return count


def read_words(words_file):
    """ (file open for reading) -> list of str

    Return a list of all words (with newlines removed) from open file
    words_file.

    Precondition: Each line of the file contains a word in uppercase characters
    from the standard English alphabet.
    """

    lists = []
   
   
   
    for line in words_file:
        word = ''

        for char in line:
           
            if char != '\n':
                word = word + char

        lists.append(word)

    return lists



def read_board(board_file):
    """ (file open for reading) -> list of list of str

    Return a board read from open file board_file. The board file will contain
    one row of the board per line. Newlines are not included in the board.
    """

    lists = []
        
   
   
    for line in board_file:
       
        #Append characters into sublist
        sub = []
        for char in line:
           
            if char != '\n':
                sub.append(char)

        if sub != []:
            lists. append(sub)

    return lists

 

Learn to Program: The Fundamentals - Week 6 Exercise

Score of 13.00 out of 13.00

Open up IDLE and try out all the code as you do the exercise!

Question 1

Consider this code:
def merge(L):
    merged = []
    for i in range(0, len(L), 3):
        merged.append(L[i] + L[i + 1] + L[i + 2])
    return merged

print(merge([1, 2, 3, 4, 5, 6, 7, 8, 9]))
What is printed by the code above?
Your Answer
Score Explanation
[123, 456, 789]


[1, 4, 7]


[6, 15, 24] Correct 1.00
[12, 15, 18]


Total
1.00 / 1.00
Question ExplanationTrace the code by hand or in the visualizer, or run the code in IDLE.

Question 2

Consider this code:
def mystery(s):
    """ (str) -> bool
    """
    matches = 0
    for i in range(len(s) // 2):
        if s[i] == s[len(s) - 1 - i]: # <-- How many times is this line reached?
            matches = matches + 1
    
    return matches == (len(s) // 2)

mystery('civil')
Trace the function call mystery('civil') using the Python Visualizer. How many times is the line marked above reached?

You entered:

Your Answer
Score Explanation
2 Correct 1.00
Total
1.00 / 1.00
Question ExplanationTrace the function call in the visualizer. Be sure to include a function call!

Question 3

Consider this code:
def mystery(s):
    """ (str) -> bool
    """
    matches = 0
    for i in range(len(s) // 2):
        if s[i] == s[len(s) - 1 - i]:
            matches = matches + 1
    
    return matches == (len(s) // 2)
Which is the best docstring description for function mystery?
Your Answer
Score Explanation
Return True if and only if there are exactly len(s) // 2 characters in s that are the same character.


Return True if and only if the number of duplicate characters in s is equal to len(s) // 2.


Return True if and only if s is equal to the reverse of s. Correct 1.00
Return True if and only if s[:len(s) // 2] is the same as s[len(s) // 2:].


Total
1.00 / 1.00
Question ExplanationFor each option, write at least one function call for which the function should return True and at least one for which it should return False. Execute the function calls to see whether they produce the expected result.
If you're confused about the meaning of s[i] == s[len(s) - 1 - i], think about an example. If s is "pipe" (so len(s) is 4) and i is 1, that asks whether s[1] is equal to the item at index s[4 - 1 - 1], or s[2].

Question 4

In one of the Week 6 lecture videos, we wrote the function shift_left. Consider this function, which shifts in the other direction:
def shift_right(L):
    ''' (list) -> NoneType

    Shift each item in L one position to the right
    and shift the last item to the first position.

    Precondition: len(L) >= 1
    '''

    last_item = L[-1]

    # MISSING CODE GOES HERE

    L[0] = last_item
Select the code fragment that correctly completes function shift_right.

Hint: the correct answer works from the end to the beginning of L.
Your Answer
Score Explanation

    for i in range(len(L)):
        L[i + 1] = L[i]




    for i in range(len(L) - 1):
        L[i] = L[i + 1]




    for i in range(1, len(L)):
        L[len(L) - i] = L[len(L) - i - 1]
Correct 1.00 During the first iteration of the loop, i refers to 1, so len(L) - i is the index of the last item in L.

As i increases, the indices move backwards through the list.

    for i in range(1, len(L)):
        L[i] = L[i + 1]



Total
1.00 / 1.00
Question ExplanationDefine each version of the function and test it by calling it in the shell or the visualizer.

Question 5

Consider the code (these type contracts get a little tough to write!):
def make_pairs(list1, list2):
    ''' (list of str, list of int) -> list of [str, int] list
    
    Return a new list in which each item is a 2-item list with the string from the
    corresponding position of list1 and the int from the corresponding position of list2.
    
    Precondition: len(list1) == len(list2)
    
    >>> make_pairs(['A', 'B', 'C'], [1, 2, 3])
    [['A', 1], ['B', 2], ['C', 3]]
    '''
    
    pairs = []
    
    # CODE MISSING HERE
        
    return pairs
Select the code fragment(s) that make the function above match its docstring description.
Your Answer
Score Explanation

    for i in range(len(list1)):
        inner_list = []
        inner_list.append(list1[i])
        inner_list.append(list2[i])
    pairs.append(inner_list)
Correct 0.25

    inner_list = []
    for i in range(len(list1)):
        inner_list.append(list1[i])
        inner_list.append(list2[i])
        pairs.append(inner_list)
Correct 0.25

    for i in range(len(list1)):
        pairs.append([list1[i], list2[i]])
Correct 0.25

    for i in range(len(list1)):
        inner_list = []
        inner_list.append(list1[i])
        inner_list.append(list2[i])
        pairs.append(inner_list)
Correct 0.25
Total
1.00 / 1.00
Question ExplanationTrace each option in the visualizer. Be sure to include a function call!

Question 6

Consider this code:
values = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Using values and indexing with non-negative indices, write an expression that evaluates to 5. Do not use addition, subtraction, or parentheses ( ) (brackets [ ] are required).

You entered:

Your Answer
Score Explanation
values[1][1] Correct 1.00
Total
1.00 / 1.00
Question ExplanationExplore this in the Python shell. Make sure to read the question carefully!

Question 7

Consider this code:
breakfast = [['French', 'toast'], ['blueberry', 'pancakes'], ['scrambled', 'eggs']]
Using breakfast and indexing with only negative indices, write an expression that evaluates to 'blueberry'. Do not use addition, subtraction, or parentheses ( ) (brackets [ ] are required).

You entered:

Your Answer
Score Explanation
breakfast[-2][-2] Correct 1.00
Total
1.00 / 1.00
Question ExplanationExplore this in the Python shell. Make sure to read the question carefully, and use only negative indices. Zero is not negative.

Question 8

Consider this code:
for i in range(2, 5):
  for j in range(4, 9):
    print(i, j)
Trace the code above in the Python Visualizer. How many times is print(i, j) executed?
Your Answer
Score Explanation
24


5


15 Correct 1.00
3


Total
1.00 / 1.00
Question ExplanationDo this in the visualizer.

Question 9

Consider this code:
def contains(value, lst):
    """ (object, list of list) -> bool

    Return whether value is an element of one of the nested lists in lst.

    >>> contains('moogah', [[70, 'blue'], [1.24, 90, 'moogah'], [80, 100]])
    True
    """

    found = False  # We have not yet found value in the list.

    # CODE MISSING HERE

    return found
Select the code fragment(s) that make the function above match its docstring description.
Your Answer
Score Explanation

    for item in lst:
        if value == item:
            value = True
Correct 0.25

    for i in range(len(lst)):
        for j in range(len(lst[i])):
            found = (lst[i][j] == value)
Correct 0.25

    for i in range(len(lst)):
        for j in range(len(lst[i])):
            if lst[i][j] == value:
                found = True
Correct 0.25

    for sublist in lst:
        if value in sublist:
            found = True
Correct 0.25
Total
1.00 / 1.00
Question ExplanationTrace each option in the visualizer.

Question 10

A file has a section at the top that has a preamble describing the contents of the file, then a blank line, then a list of high temperatures for each day in January all on one line, then a list of high temperatures for each day in February all on one line, then lists for March, April, and so on through December, each on one line. There are thousands of lines of information after that temperature data that you aren't currently interested in.
You want to write a program that prints the average of the high temperatures in January. Which of the four file-reading approaches should you use?
Hint: review the Reading Files lecture.
Your Answer
Score Explanation
The readlines approach


The read approach


The readline approach Correct 1.00
The for line in file approach


Total
1.00 / 1.00
Question ExplanationYou want to process only part of the file, the line containing January high temperatures. Which approach from the Reading Files lecture is this?

Question 11

Consider this code:
# data_file refers to a file open for reading.
for line in data_file:
    print(line)
The program above prints the lines of the file but adds an extra blank line after each line. Select the code fragment(s) that when used as replacement(s) for print(line) will print the lines without extra blank lines.

Note: use help to find out information about any functions or methods that you are not familiar with.
Your Answer
Score Explanation
print(line.strip()) Correct 0.25 This strips all whitespace from the beginning and end of each line, rather than just the newline at the end.
print(line - '\n') Correct 0.25
print(line, end='') Correct 0.25
print(line.rstrip('\n')) Correct 0.25
Total
1.00 / 1.00
Question ExplanationCreate a variable line that refers to a string ending with the newline character ('\n') and run the different options. Make sure you are printing each line without an extra newline at the end, and without modifying the line in any other way.

Question 12

Consider this code:
def lines_startswith(file, letter):
    """ (file open for reading, str) -> list of str

    Return the list of lines from file that begin with letter. 
    The lines should have the newline removed.

    Precondition: len(letter) == 1
    """

    matches = []

    # CODE MISSING HERE

    return matches
Select the code fragment(s) that make the function above match its docstring description.
Your Answer



    for line in file:
        if letter in line:
            matches.append(line.rstrip('\n'))
Correct 0.25

    for line in file:
        matches.append(line.startswith(letter).rstrip('\n'))
Correct 0.25

    for line in file:
        if line.startswith(letter):
            matches.append(line.rstrip('\n'))
Correct 0.25

    for line in file:
        if letter == line[0]:
            matches.append(line.rstrip('\n'))
Correct 0.25
Total
1.00 / 1.00
Question ExplanationTrace each option in the visualizer.

Question 13

Consider this code:
def write_to_file(file, sentences):
    """ (file open for writing, list of str) -> NoneType

    Write each sentence from sentences to file, one per line.

    Precondition: the sentences contain no newlines.
    """

    # CODE MISSING HERE
Select the code fragment(s) that make the function above match its docstring description.
Your Answer
Score Explanation

    for s in sentences:
        file.write(s)
        file.write('\n')
Correct 0.20

    file.write(sentences)
Correct 0.20

    for s in sentences:
        file.write(s + '\n')
Correct 0.20

    for s in sentences:
        file.write(s)
    file.write('\n')
Correct 0.20

    for s in sentences:
        file.write(s)
Correct 0.20
Total
1.00 / 1.00
Question ExplanationRun the code and see what the files look like.