Saturday, September 28, 2013

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.