LEAD Computer Science - Lab 1

Due: Friday, July 13 at 4pm

This lab will give you a chance to warm up with the Python language, and to begin exploring some of the functionality provided for strings and lists.  This lab will be more focused on simple problems and functions so that you can become familiar with the language. Future labs will focus on larger (and more interesting) programming projects.

Since we will be completing quite a few labs in the next few weeks, we want to keep things organized by putting each lab into its own directory. Start a Command Prompt window and set up a new directory lab1 by executing these commands:

mkdir lab1
cd lab1

This is where you will complete this lab. Start WingIDE and complete the following sections, saving everything into a single file lab1.py. The first time you save your program, use the "File/Save As" command to save it into the lab1 directory. Make sure to save your work often! You can save your work anytime by pressing Cmd-S; most experienced programmers do this frequently, automatically, just by habit.

For the exercises where you are asked to evaluate some Python expression or answer a question, write the answer in a comment, along with the exercise number and subsection. For instance, if you are asked to evaluate 2 + 2 for exercise 3, section 6, you would write:

  # Ex 3.6:  2 + 2 --> 4

You can use multiple lines if you like, but make sure each line is a comment.

For the exercises where you are asked to write some Python code, write the code with a preceding comment indicating the problem number (and subsection). For instance, if you were asked to write a function of one input which returns the input unchanged as the answer to exercise 5, section 2, you could write:

  # Ex 5.2:
  def identity(x):
      return x

The entire file lab1.py should be valid Python.  In other words, running python lab1.py at the command-prompt shouldn't produce any errors.

Note that when you run python lab1.py, the interpreter will simply execute the entire contents of the file and then terminate.  However, if you want to test some of the functions you write, you should load the file into WingIDE and hit the right-arrow button to send the contents to the "python shell" in WingIDE. It will run the file and then give you a prompt; you can then enter python commands at the prompt.

Part A:  Python Expressions

Write a comment in your lab1.py file, something like this, so that we know what part the answers are for:

#========
# Part A
#========

Then, write the answers to these questions as Python comments in your file.  Make sure to indicate what problem each answer is for.

Each problem specifies the approximate number of minutes that the average student is expected to take on the problem.  If you exceed this time estimate by a lot, please ask for help!

  1. [10] For each of the following expressions, what value will the expression give? Don't just guess; verify your answers by typing the expressions into the Python shell.

    1. 9 - 3
    2. 8 * 2.5
    3. 11 / 4
    4. 11 / 4.0
    5. 11.0 / 4
    6. 11 % 4                     (In Python, % is the remainder operator)
    7. 11 % 3.5
    8. 4 + 3 * 5
    9. (4 + 3) * 5
    10. In one or two sentences, briefly explain your answers for parts 3 through 5 above.  (Hint: What are the types of the operands for each of these expressions?)

  2. [10] Python includes a lot of operators of the form op=, where op is one of the standard operators. For instance, the following are all operators: += -= *= /= %=. The meaning of these operators is as follows:

    x op= y
    

    is the same as

    x = x op y
    

    For instance, x += y is the same as x = x + y and y -= 2 is the same as y = y - 2. For each of the following statements, what will be the value of the variable x after the statement has been executed? Assume that the statements are entered into the Python shell one after another, so that subsequent statements can depend on the values of previous ones.

    1. x = 100
    2. x = x + 10
    3. x += 20
    4. x = x - 40
    5. x -= 50
    6. x *= 3
    7. x /= 5
    8. x %= 3
  3. [5]  Write a step-by-step description of what happens when Python evaluates the statement x += x - x when x has the initial value of 3. What is x after the statement has been evaluated?

  4. [5]  What are the values of the following expressions? (If there are multiple lines in a question, give the value of the expression on the final line.) If an expression gives an error, write the error message.

    1. "foo" + 'bar'

    2. "foo" 'bar'

    3. a = 'foo'
      b = "bar"
      a + b

    4. a = 'foo'
      b = "bar"
      a b

    For these expressions, assume that a = 'hello'.  As before, if an expression gives an error, write the error message.

    1. a[1]

    2. a[-1]

    3. a[-4]

    4. a[5]

    5. a[-5]

  5. [5]  Rewrite the following string using single or double quotes instead of triple quotes (but without using any operators or function calls):

    '''A
    B
    C'''

  6. [10] Write a single Python expression which will generate a string of 80 '-' characters. The expression itself shouldn't be longer than 10 characters.

  7. [15] Given variables x and y, which refer to the values 3 and 12.5 respectively, write a line of code using print to display each of the following messages. When numbers appear in the messages, the variables x and y should be used in the print statement. Use the % formatting operator and a format string for each example.

    1. The rabbit is 3.
    2. The rabbit is 3 years old.
    3. 12.5 is average.
    4. 12.5 * 3
    5. 12.5 * 3 is 37.5.

Part B:  Python Functions

As with Part A, make sure to add a comment in your lab1.py file to indicate the start of Part B.

  1. [10] Write a function called quadratic that takes four input arguments a, b, c, and x and computes the value of the quadratic expression

    ax2 + bx + c

    for those values of a, b, c, and x. Note that ** is the power operator in Python, though you don't actually have to use that. What else could you use if you don't use the ** operator?

    Important Note:  this function should return its result, not print the result.  In general, the vast majority of the functions you write will return a value, not print it.  Of course, when you invoke functions from the interactive prompt, the result is automatically printed, but don't be confused by this - the function should return the result, not print it.

  2. [10] Write a function called print_title that takes one string argument s, and prints s in upper-case, surrounded with a border, like this:

    >>> print_title('the quick brown fox')
    +---------------------+ | THE QUICK BROWN FOX | +---------------------+

    The function should also remove any leading or trailing whitespace on the input string before printing it:

    >>> print_title('  the lazy dog     ')
    +--------------+ | THE LAZY DOG | +--------------+

    Note:  This function is an exception to the previous note; its sole purpose is to print a string with special formatting.  Note that we have indicated this by giving the function the name print_title.  All other functions in this lab will return their values, not print them.

  3. [30] DNA is composed of four distinct base pairs: adenine (A), cytosine (C), guanosine (G), and thymine (T). In a DNA molecule, A bases pair with T bases and C bases pair with G bases. A value of interest is the proportion of C/G bases in a DNA molecule, since C/G bases bind more strongly than A/T bases (and thus, a DNA molecule with a large proportion of C/G bases is more stable than one with a large proportion of A/T bases). Given a DNA sequence, this can easily be computed by counting up the number of each base, and taking the ratio of the (G or C) bases as a proportion of the total.

    Use Python's built-in help() function to learn about the count() method of Python's strings (typing help("".count) at the Python interactive prompt is one way to do this). Then use this to write a function called GC_content which takes in a string representing a DNA sequence and returns a single float, which represents the proportion of the bases which are either G or C. You may assume that the input string has only A, C, G, or T bases. For instance:

    GC_content("ACCAGTGTAG") --> 0.5
    GC_content("ATATATATA") --> 0.0
    GC_content("GCGGCCATGCATGGGG") --> 0.75

    One pitfall here is that dividing two integers throws out the remainder, so you will want to convert the numerator and denominator of the ratio to floats using the float() function (built-in to Python) before doing the division.

    Make sure you test your function on the examples given, no matter how sure you are that it works correctly!

  4. [15] Write another DNA analysis function which again takes one argument, a string composed of only the letters 'A', 'C', 'G', and 'T' representing a DNA string. This function will return another string composed of the same four letters, representing the complement of the original string. This means that the result string will have an 'A' where the original string has a 'T', a 'C' where the original string has a 'G', a 'G' where the original string has a 'C', and a 'T' where the original string has an 'A'. Example:

        >>> complement('ACGGATC')  
        'TGCCTAG'
    

    Use string operations only (don't convert the string to a list). You may find the += operation on strings to be useful.

Part C:  Python Lists

Again, add a comment to indicate the start of Part C. Also, make sure to test your code to verify that it works correctly. You should always assume that untested code is broken, because it usually is!

  1. [15] Python includes a built-in function sum that can compute the sum of a list of numbers:

    >>> sum([1, 2, 3, 4])
    10
    >>> sum([])
    0

    Write a function called product that also takes a list of numbers, then computes and returns the product of the list. If the list is empty, it should return 1. Examples:

    >>> product([])
    1
    >>> product([2, 2, 3, 3, 10])
    360
    
  2. [15] The factorial of a non-negative integer is defined to be the product of all the integers from 1 up to the integer. As a special case, the factorial of 0 is defined to be 1.  Use the range function and the product function you just defined to create a function called factorial which takes a single argument (a non-negative integer) and returns the factorial of that integer.  Examples:

    >>> factorial(0)
    1
    >>> factorial(5)  # 5 * 4 * 3 * 2 * 1
    120
    
  3. [20] The remove method of lists is useful, but it has the limitation that it will only remove the first matching element it finds in a list. Write a function called remove_all which takes two arguments: a list (which you can assume to contain only integers) and a value (also an integer). It will remove all copies of the value from the list. It will do this by using a for loop and the count method on lists to determine if there are any more matching elements in the list. Each time through the list, the remove method will be called to remove one more matching element from the list. The function won't return anything, because the list will be changed in place. Examples:

    >>> lst = [1, 1, 3, 1, 4, 1, 5, 1, 6, 1, 1, 7, 1]
    >>> remove_all(lst, 1)
    >>> lst
    [3, 4, 5, 6, 7]
    
  4. [20] You've learned the Python syntax for <item> in <list> in class. But as we've mentioned several times, Python likes to overload its syntax to mean different things. The in keyword, in particular, can be used not just as part of a for loop but also to test for membership in a list. For instance:

    >>> 4 in [1, 2, 3, 4, 5]
    True
    >>> 'foo' in ['foo', 'bar', 'baz']
    True
    >>> 'cat' in ['fluffy', 'morris', 'sylvester']
    False
    

    In each case, the interpretation is the same: is this item in this list? Let's use this to write a function called any_in. It will take two lists as arguments, and will return True if any of the elements of the first list are equal to any of the elements of the second one. Examples:

    >>> any_in([1, 2, 3], [1, 5, 9, 11, 43])
    True
    >>> any_in([1, 2, 3], [])
    False
    >>> any_in([], [1, 2, 3])
    False
    >>> any_in([], [])
    False
    >>> any_in(['foo', 'bar', 'baz'], ['to', 'be', 'or', 'not', 'to', 'be'])
    False
    >>> any_in(['and', 'or', 'not'], ['to', 'be', 'or', 'not', 'to', 'be'])
    True
    

Submitting Your Work

Once you have completed all parts of the assignment, you can submit your work to csman. Log in to csman and submit the file lab1.py for Lab 1. Then you are all finished!


Copyright (c) 2012, California Institute of Technology. All rights reserved.
Last updated July 10, 2012.