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.

Learn to Program: The Fundamentals - Week 5 Exercise

Score of 13.75 out of 14.00
Open up IDLE and try out all the code as you do the exercise!

Question 1

Select the expression(s) that evaluate to True.
Your Answer
Score Explanation
[1, 2, 3] in len('mom') Correct 0.25
len('mom') in [1, 2, 3] Correct 0.25
int('3') in [len('a'), len('ab'), len('abc')] Correct 0.25
'3' in [1, 2, 3] Correct 0.25
Total
1.00 / 1.00
Question ExplanationEvaluate each of these expressions in the Python shell and, if the results surprise you, you should also evaluate each subexpression.

Question 2

Consider this code:
def mystery(s):
    i = 0
    result = ''

    while not s[i].isdigit():
        result = result + s[i]
        i = i + 1

    return result
Select the function call(s) that result in an error.
Your Answer
Score Explanation
mystery('abc') Correct 0.25
mystery('abc123') Correct 0.25
mystery('123') Correct 0.25
mystery('123abc') Correct 0.25
Total
1.00 / 1.00
Question ExplanationRun the code. To understand why the error occurs (or does not), trace the code in the visualizer.

Question 3

Consider this code:
def example(L):
    """ (list) -> list
    """
    i = 0
    result = []
    while i < len(L):
        result.append(L[i])
        i = i + 3
    return result
Which is the best docstring description for function example?
Your Answer
Score Explanation
Return a list containing every third item from L starting at index 0. Correct 1.00
Return an empty list.


Return a list containing every third index from L starting at index 0.


Return a list containing the items from L starting from index 0, omitting every third item.


Total
1.00 / 1.00
Question ExplanationRun the code several times, passing various lists as arguments, to gain a better understanding of what it does.

Question 4

def compress_list(L):
    """ (list of str) -> list of str

    Return a new list with adjacent pairs of string elements from L
    concatenated together, starting with indices 0 and 1, 2 and 3,
    and so on.

    Precondition: len(L) >= 2 and len(L) % 2 == 0

    >>> compress_list(['a', 'b', 'c', 'd'])
    ['ab', 'cd']
    """
    compressed_list = []
    i = 0

    while i < len(L):
        compressed_list.append(L[i] + L[i + 1])
        # MISSING CODE HERE

    return compressed_list
Select the missing line of code.
Your Answer
Score Explanation
i = i + 2 Correct 1.00
i = i + 1


i = i * 2


i = i + i


Total
1.00 / 1.00
Question ExplanationRun the code to gain a better understanding of what it does and what effect each choice has.

Question 5

What is the sum of the even numbers from 524 through 10508, inclusive? Hint: write a while loop to accumulate the sum and print it. Then copy and paste that sum. For maximum learning, do it with a for loop as well, using range.

You entered:

Your Answer
Score Explanation
27541388 Correct 1.00
Total
1.00 / 1.00
Question ExplanationStart by solving a simpler problem, such as printing the even integers between 2 and 10. Make sure that you print 2, 4, 6, 8, and 10. Then introduce a variable, perhaps called sum, that starts at 0, and in each iteration adds the current integer to sum. The sum of the even numbers from 2 through 10, inclusive, is 30. Then reattempt the question.

Question 6

Consider this code:
def while_version(L):
    """ (list of number) -> number
    """
    i = 0
    total = 0

    while i < len(L) and L[i] % 2 != 0:
        total = total + L[i]
        i = i + 1

    return total
The while loop stops as soon as an even number is found, and the sum of all the previous numbers is returned. The four functions below use a for loop to try to accomplish the same task, although they keep iterating through all of the numbers in L regardless of whether the numbers are even or odd. Only one of them returns the same value as function while_version. Which one is it?
Your Answer
Score Explanation

def for_version(L):
    found_even = False
    total = 0

    for num in L:
        if num % 2 != 0 and not found_even:
            total = total + num
        else:
            found_even = True
 
    return total
Correct 1.00

def for_version(L):
    found_even = False
    total = 0

    for num in L:
        if num % 2 != 0:
            total = total + num
        elif not found_even:
            found_even = True

    return total




def for_version(L):
    found_even = False
    total = 0

    for num in L:
        if num % 2 != 0:
            total = total + num
        found_even = True

    return total




def for_version(L):
    found_even = False
    total = 0

    for num in L:
        if num % 2 != 0:
            total = total + num
            found_even = True

    return total



Total
1.00 / 1.00
Question ExplanationPay close attention to the variables involved in the loop condition: i and L. Read through the code or trace it in the visualizer to determine what that while loop does and when it exits. You should also run each of the for_version functions.

Question 7

Consider this code:
>>> numbers = [1, 4, 3]
>>> # MISSING CODE HERE
>>> print(numbers)
[3, 4, 1]
Which of the following code fragments(s) could be the missing code in the program above?
Your Answer
Score Explanation
numbers.reverse() Correct 0.25
reverse(numbers) Correct 0.25
numbers = reverse(numbers) Correct 0.25
numbers = numbers.reverse() Correct 0.25
Total
1.00 / 1.00
Question ExplanationRun the code and try each code fragment.

Question 8

Consider this code:
fruits = ['banana', 'apple', 'pear', 'peach']
fruits.insert(fruits.index('pear'), 'watermelon')
print(fruits)
What is printed by the code above?
Your Answer
Score Explanation
['banana', 'apple', 'watermelon', 'pear', 'peach'] Correct 1.00
['banana', 'watermelon', 'apple', 'pear', 'peach']


['banana', 'apple', 'watermelon', 'peach']


['banana', 'apple', 'pear', 'watermelon', 'peach']


Total
1.00 / 1.00
Question ExplanationRun the code and read the help for list.index and list.insert.

Question 9

Your younger sibling has just discovered music from the 1970's. They have put together a playlist of the same 5 songs repeated again and again. Here are the songs:
  • ABC by The Jackson 5
  • Venus by Shocking Blue
  • Lola by the Kinks
  • Let It Be by the Beatles
  • Cecilia by Simon and Garfunkel

  • Here is an example of their playlist:
    ['Lola', 'Venus', 'Lola', 'Lola', 'Let It Be', 'Lola', 'ABC', 'Cecilia', 'Lola', 'Lola']
    You want to make sure that Lola gets played at most 3 times, so you want to complete this function that edits the playlist:
def cap_song_repetition(playlist, song):
    '''(list of str, str) -> NoneType

    Make sure there are no more than 3 occurrences of song in playlist.
    '''
Select the loop(s) that accomplish this.
Your Answer
Score Explanation

    while playlist.count(song) > 3:
        playlist.pop(playlist.index(song))
Correct 0.25

    while playlist.count(song) > 3:
        playlist.remove(song)
Correct 0.25

    while playlist.count(song) >= 3:
        playlist.remove(song)
Correct 0.25

    while playlist.count(song) > 3:
        playlist.pop(song)
Correct 0.25
Total
1.00 / 1.00
Question ExplanationLook at help(list.remove) and help(list.pop) and see if you can determine which uses are correct. You can also enter the different function completions into IDLE and test them on an equivalent example:
>>> playlist = ['A', 'B', A', 'A', 'C', 'A', 'D', 'E', 'A', 'A']
>>> cap_song_repetition(playlist, 'A')
>>> print(playlist)

Question 10

Consider this code:
>>> a = [1, 2, 3]
>>> b = a
>>> # MISSING CODE HERE
>>> print(a, b)
[1, 'A', 3] [1, 'A', 3]
Which of the following code fragments(s) could be the missing code in the program above?
Your Answer
Score Explanation

a[1] = 'A'
Correct 0.25

b[-2] = 'A'
Correct 0.25

b[1] = 'AB'
a[1] = a[1][0]
Correct 0.25

a = [1, 'A', 3]
b = [1, 'A', 3]
Correct 0.25
Total
1.00 / 1.00
Question ExplanationRun the code, substituting each code fragment in for the missing code. Note that if a[1] is "CAT", then a[1][0] is "C".

Question 11

Consider this code:
>>> a = [1, 2, 3]
>>> b = [1, 2, 3]
>>> # MISSING CODE HERE
>>> print(a, b)
[1, 'A', 3] [1, 'A', 3]
Which of the following code fragments(s) could be the missing code in the program above?
Your Answer
Score Explanation

a = [1, 'A', 3]
b = [1, 'A', 3]
Correct 0.25

a[1] = 'A'
Correct 0.25

b[-2] = 'A'
Inorrect 0.00

b[1] = 'AB'
a[1] = a[1][0]
Correct 0.25
Total
0.75 / 1.00
Question ExplanationRun the code, substituting each code fragment in for the missing code. Note that if a[1] is "CAT", then a[1][0] is "C".

Question 12

Consider this code:
def increment_items(L, increment):
    i = 0
    while i < len(L):
        L[i] = L[i] + increment
        i = i + 1

values = [1, 2, 3]
print(increment_items(values, 2))
print(values)
What is printed by the program above?
Your Answer
Score Explanation

None
[3, 4, 5]
Correct 1.00

None
[1, 2, 3]




[3, 4, 5]
[1, 2, 3]




[3, 4, 5]
None



Total
1.00 / 1.00
Question ExplanationRun the code.

Question 13

Select the code fragment(s) that print [3, 6, 9].
Your Answer
Score Explanation

values = []
for num in range(3, 10, 3):
    values.append(num)
print(values)
Correct 0.25

values = []
for num in range(1, 4):
    values.append(num * 3)
print(values)
Correct 0.25

values = []
for num in range(1, 3):
    values.append(num * 3)
print(values)
Correct 0.25

values = []
for num in range(3, 9, 3):
    values.append(num)
print(values)
Correct 0.25
Total
1.00 / 1.00
Question ExplanationCall help(range) to learn about the function range and its two optional arguments.

Question 14

Select the function calls to range that, when used to fill in the blank, cause the code to produce the results below.
for num in __________________:
    print(num)
The loop should print this:
3
11
19
Your Answer
Score Explanation
range(3, 20, 8) Correct 0.25
range(3, 23, 8) Correct 0.25
range(3, 19, 8) Correct 0.25
range(3, 8, 20) Correct 0.25
Total
1.00 / 1.00
Question ExplanationCall help(range) to learn about the function range and it's two optional arguments.

Wednesday, September 18, 2013

Learn to Program: The Fundamentals - Assignment 2 - Week 4

Learn to Program: The Fundamentals - Assignment 2

A2 Problem Domain: Deoxyribonucleic Acid (DNA)

The problem domain for A2 is Deoxyribonucleic Acid (DNA), the double-stranded molecule that encodes genetic information for living organisms. DNA is made up of four kinds of nucleotides, which are molecules that bond together to form DNA sequences.
The four nucleotides are adenine (A), guanine (G), cytosine (C), and thymine (T). Each strand of DNA is a sequence of nucleotides, for example AGCTAC. In a program, we will use a string representation of this, "AGCTAC".
DNA has 2 strands in a double helix. The nucleotides in one strand are bonded to the nucleotides in the other strand. A and T can be bonded together, and thus complement each other; similarly, C and G are complements of each other.
You can see a picture of this on the Wikipedia page for DNA. The two strands in DNA are complementary because each nucleotide in one strand is bonded with its complement in the other strand. Thus, given the DNA sequence ACGTACG, its complementary strand is TGCATGC.

Terminology in this handout

A DNA sequence is a sequence of nucleotides, such as TCATGT.

What to do


Step 2: Write functions get_length, is_longer, count_nucleotides, and contains_sequence. (Be sure to test your code with empty strings where appropriate.)

For these functions, you may use built-in functions, str operations (for example: in, +, indexing), and str methods.
Function name:
(Parameter types) -> Return type
Description
get_length:
(str) -> int
The parameter is a DNA sequence. Return the length of that sequence.
is_longer:
(str, str) -> bool
The two parameters are DNA sequences. Return True if and only if the first DNA sequence is longer than the second DNA sequence. (If they are the same length, return False.)
count_nucleotides:
(str, str) -> int
The first parameter is a DNA sequence and the second parameter is a nucleotide ('A', 'T', 'C' or 'G'). Return the number of times the nucleotide occurs in the DNA sequence.
contains_sequence:
(str, str) -> bool
The two parameters are DNA sequences. Return True if and only if the first DNA sequence contains the second DNA sequence.

 def get_length(dna):
    """ (str) -> int

    Return the length of the DNA sequence dna.

    >>> get_length('ATCGAT')
    6
    >>> get_length('ATCG')
    4
    """
    return len(dna)


def is_longer(dna1, dna2):
    """ (str, str) -> bool

    Return True if and only if DNA sequence dna1 is longer than DNA sequence
    dna2.

    >>> is_longer('ATCG', 'AT')
    True
    >>> is_longer('ATCG', 'ATCGGA')
    False
    """
    return len(dna1) > len(dna2)


def count_nucleotides(dna, nucleotide):
    """ (str, str) -> int

    Return the number of occurrences of nucleotide in the DNA sequence dna.

    >>> count_nucleotides('ATCGGC', 'G')
    2
    >>> count_nucleotides('ATCTA', 'G')
    0
    """
    number = 0
    for num in dna:
        if num == nucleotide:
           number += 1
    return number

def contains_sequence(dna1, dna2):
    """ (str, str) -> bool

    Return True if and only if DNA sequence dna2 occurs in the DNA sequence
    dna1.

    >>> contains_sequence('ATCGGC', 'GG')
    True
    >>> contains_sequence('ATCGGC', 'GT')
    False

    """
    return dna2 in dna1

 

Step 3: Write functions is_valid_sequence and insert_sequence.

There is no starter code for these functions. Use the design recipe to complete them. We have given you some suggestions for examples to try, but you should come up with more on your own based on the descriptions.
For these functions, you may use built-in functions and str operations (for example: in, +, indexing).

Do not use str methods.

Function name:
(Parameter types) -> Return type
Description
is_valid_sequence:
(str) -> bool
The parameter is a potential DNA sequence. Return True if and only if the DNA sequence is valid (that is, it contains no characters other than 'A', 'T', 'C' and 'G').
There are at least 2 ways to approach this. One way is to count the number of characters that are not nucleotides and then at the end check whether there were more than zero. Another way is to use a Boolean variable that represents whether you have found a non-nucleotide character; it would start off as True and would be set to False if you found something that wasn't an 'A', 'T', 'C' or 'G'.
You should construct examples that contain only 'A's, 'T's, 'C's and 'G's, and you should also create examples that contain other characters. A string is not a valid DNA sequence if it contains lowercase letters.
insert_sequence:
(str, str, int) -> str
The first two parameters are DNA sequences and the third parameter is an index. Return the DNA sequence obtained by inserting the second DNA sequence into the first DNA sequence at the given index. (You can assume that the index is valid.)
For example, If you call this function with arguments 'CCGG', 'AT', and 2, then it should return 'CCATGG'.
When coming up with more examples, think about where the second DNA sequence might be inserted: what are the extremes?
Once you have finished writing these functions, in IDLE, choose Run -> Run Module. In the shell, test your function by running some example function calls.

 

 def is_valid_sequence(dna):
    ''' (str) -> bool
    Return True if only DNA sequence is valid.

    >>> is_valid_sequence('ATCG')
    True
    >>> is_valid_sequence('LTPROCKS')
    False
    '''
    for n in dna:
        if n not in('ATCG'):
            return False
    else:
        return True

def insert_sequence(dna1,dna2,index):
    ''' (str,str,int) -> str
    Return the DNA sequence obtained by inserting the second DNA sequence
    into the first DNA sequence at the given index.

     >>> insert_sequence('CCGG','AT',2)
     CCATGG
     '''
    return dna1[:index] + dna2 + dna1[index:]

 

Step 4: Write functions get_complement and get_complementary_sequence.

There is no starter code for these functions. Use the design recipe to complete them. We have given you some suggestions for examples to try, but you should come up with more on your own based on the descriptions.
For these functions, you may use built-in functions and str operations (for example: in, +, indexing).

Do not use str methods.

Function name:
(Parameter types) -> Return type
Description
get_complement:
(str) -> str
The first parameter is a nucleotide ('A', 'T', 'C' or 'G'). Return the nucleotide's complement.
We have intentionally not given you any examples for this function. The Problem Domain section explains what a nucleotide is and what a complement is.
get_complementary_sequence:
(str) -> str
The parameter is a DNA sequence. Return the DNA sequence that is complementary to the given DNA sequence.
For exmaple, if you call this function with 'AT' as the argument, it should return 'TA'.
Once you have finished writing these functions, in IDLE, choose Run -> Run Module. In the shell, test your function by running some example function calls.


def get_complement(n):
    '''(str) -> str
    Return the complement of a nucleotide.

    >>> get_complement('A')
    T
    >>> get_complement('C')
    G
    '''

    if n == 'A':
        return 'T'
    elif n == 'T':
        return 'A'
   
    if n == 'C':
        return 'G'
    elif n == 'G':
        return 'C'

def get_complementary_sequence(dna):
    '''(str) -> str
    Return the complement of a given DNA sequence.

    >>> get_complementary_sequence('ATCGGACT')
    TAGCCTGA
    >>> get_complementary_sequence('GCACTCC')
    CGTGAGG
    '''

    complementary_seq = ''
    for n in dna:
        complementary_seq += get_complement(n)
    return complementary_seq