Due date

This assignment is due on Thursday April 11th, at 11:30 PM.

Coverage

This assignment covers the material up to lecture 4, as well as all the readings up to reading 7.

What to hand in

You will hand in a single file called hw1.py. This will consist of Python code and comments. For this assignment, only parts A and B have anything you need to hand in.

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 part B, exercise 3, you would write:

# Ex B.3:  2 + 2 --> 4

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

We have provided a starting template in this format here, which you can start with (make sure to rename it hw1.py).

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 part A, exercise 5, you could write:

# Ex B.5


def identity(x):
    return x

The code itself should not be commented out, of course, because we will need to run it to make sure it works correctly. Feel free to add more comments as desired (within reason).

How to submit your assignment

Submit your assignment on CodePost.

Time hints

Numbers in bold at the start of problems (e.g. [10]) are a crude estimate of the time (in minutes) the problem should take. Technically, they are an upper bound i.e. you may complete them in less time, but it shouldn’t take more time than the listed time. If it seems like a problem is taking you disproportionately long to complete (e.g. if you are spending hours on a problem rated [10]), that is a hint that you might want to talk to a TA. These numbers assume that you have attended the lectures and have done the portions of the assignment that precede it.

Getting Python set up on your computer

Before you attempt this assignment, make sure you have Python and Visual Studio Code set up on your computer as described in the setup document on the course website.

Part A: Course policies

We really want you to read the collaboration policies page for the course. To make sure that you do, we are going to describe some scenarios here and ask you to identify whether they are allowed or not allowed. Write your answers as Python comments. If you think a questions doesn’t have a simple "allowed" or "not allowed" answer, write down your understanding of under what circumstances the scenario is allowed or not. In the scenarios, the word "problem" means "a problem on a CS 1 assignment".

  1. Another student is having trouble with a problem and asks you if they can see your code to see how you did it. You show them.

  2. You get on a Skype call with another student who needs help on their CS 1 assignment. You look at their code and offer comments.

  3. You get on a Zoom call with a TA and show them how you tried to solve a problem, even though it isn’t working yet.

  4. You post your partially-working solution to one of the assignment problems to Discord where everyone can see it.

  5. Your friend asks you about the general strategy you used to solve a problem. You tell them, but you don’t show them or describe any code you wrote.

  6. You ask someone who took the course last year if you can look at their solution to a problem. They show you what they did.

  7. You ask someone who has never taken the course how to solve a problem. They show you how they would have written the code.

  8. You are on a phone call with a friend who is taking the course and you mention that you are having trouble with a problem. They tell you in words what they did, giving details about the code that they wrote.

  9. You find a public Github code repository of solutions to CS 1 problems from previous years. You compare your solutions to the ones in the repository.

Part B: Exercises

In this section we will do some basic programming exercises to test your understanding of the lecture material and to let you experiment with the Python interpreter. We will also introduce you to a few features of Python that we didn’t talk about in the lectures.

1. Expressions

[10]

For each of the following expressions, what value will the expression give? Verify your answers by typing the expressions into the Python interpreter. Write your answers as Python comments.

  1. 8 - 5

  2. 6 * 2.5

  3. 51 / 2

  4. 51 / -2

  5. 51 % 2

  6. 51 % -2

  7. -51 % 2

  8. 51 / -2.0

  9. 1 + 4 * 5

  10. (1 + 4) * 5

2. Shortcut assignment operators

[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 interpreter one after another, so that subsequent statements can depend on the values of previous ones. Write your answers as Python comments.

  1. x = 120

  2. x = x - 10

  3. x += 20

  4. x = x - 90

  5. x -= 10

  6. x *= 4

  7. x /= 5

  8. x %= 4

3. Evaluation walkthrough

[10]

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? Write your answer as a Python comment. (Don’t just write the answer or you won’t get credit. Write at least a couple of sentences.)

4. Complex numbers

[10]

Complex numbers are the sum of a real number and an imaginary number. An imaginary number is just a real number multiplied by the square root of -1. The square root of -1 is often called i or j. Python allows you to enter complex numbers directly, in the form Yj (for imaginary numbers) and X+Yj (for complex numbers).

What are the values of the following expressions?

  1. 1j + 2.4j

  2. 4j * 4j

  3. (1+2j) / (3+4j)

What are the results of the following two expressions?

  1. (1+2j) * (1+2j)

  2. 1+2j * 1+2j

And one more question:

  1. Why do you think the last two expressions give different results? What does this tell you about the way Python handles complex numbers?

Remember operator precedence.

Write all your answers as Python comments.

5. Functions on complex numbers

[10]

Not all functions act the way you would expect them to. Enter the following into the Python interpreter:

>>> import math
>>> math.sqrt(-1.0)

This will give the following error message:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: math domain error

That means that the sqrt function can’t handle square roots of negative numbers. Fortunately, the cmath (complex math) module exists which can handle problems like these. Now try this:

>>> import cmath
>>> cmath.sqrt(-1.0)

Notice that this does give the expected answer of 1j.

What are the values of the following expressions?

  1. cmath.sin(-1.0+2.0j)

  2. cmath.log(-1.0+3.4j)

  3. cmath.exp(-cmath.pi * 1.0j)

Finally, why do you think it’s a better idea to write

import math
import cmath

than

from math import *
from cmath import *

in a program? For full credit, your answer must be clearly justified; we are looking for you to demonstrate understanding of this difference as motivated in lecture/the readings.

Write all your answers as Python comments.

6. String expressions

[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. Write all answers as Python comments.

1.

"Lorem" + 'Ipsum'

2.

"Lorem" 'Ipsum'

3.

a = 'Lorem'
b = "Ipsum"
a + b

4.

a = 'Lorem'
b = "Ipsum"
a b

5.

month = "April"
days = 30
days + " days hath " + month

7. Fun with quotes and slashes

[5]

Define a variable called question as a string enclosed by single quote characters (not double/triple quotes). When evaluated with print(question), the output should be exactly as the following (do not use a print statement in your answer though). Write the answer inside a Python comment (as a single-line).

How many /'s and //'s can a Sandslash "slash"?

8. String generation

[10]

Write a single Python expression which will generate a string of 70 '-' characters. The expression itself shouldn’t be longer than 10 characters. Write the answer inside a Python comment.

9. A string puzzle

[5]

Write a single Python string which, when printed using Python’s print function, will print:

Step 1
Step 2
Step 3

(without any leading or trailing spaces on any of the lines). Write the string inside a Python comment.

10. String formatting

[15]

Assume that you are starting with this code (which you may copy into your assignment):

x = 3
y = 4.25

For each of the following messages, write a line of code using print that will display the message. Where numbers appear in the messages, the variables x and y should be used in the print function call. Use the f'' format string syntax (not the format method or any str function call) for each example that uses a variable. In this case, write your answers as Python code (not inside a comment). Note: the original wording had '9 months' for Lorem's age instead of '3 years' but x = 9 wasn't updated to x = 3 (the intended value). We will be lenient on what your initial assignment for x is (though 3 will be easier) as long as your answers still follow the requirements and match the given results.

  1. Lorem is 3.

  2. Lorem is 3 years old.

  3. A puppuccino is $4.25.

  4. 4.25 * 3

  5. 4.25 * 3 is 12.75.

11. Terminal input

[10]

Use input to prompt the user for a number. Store the number entered as a floating-point number (a Python float) in a variable named num, and then print the contents of num. Use the prompt string "Enter a number: " as the argument to input. Write the answer as Python code (not in a comment).

12. Quadratic expressions

[10]

Write a function called quadratic that takes four arguments a, b, c, and x and computes and returns the value of the quadratic expression a x2 + b x + 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 it. (What else could you use if you don’t use the ** operator?)

Write your answer as Python code (not in a comment).

For full credit, also add a docstring to your function so that typing:

help(quadratic)

in the Python interpreter will print out a description of what the function does, what its input argument should be, and what its return value represents. Refer to lectures and the Code Quality Guide for what is expected for function docstrings.

13. DNA

[30]

DNA is composed of four distinct bases: 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 type of base in the sequence, and taking the ratio of the (G or C) bases as a proportion of the total.

Use Python’s 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 and you do not need to handle case-sensitivity (though you may as an added challenge, such that "A" is equivalent to "a" in your answer, and so on). For instance:

>>> gc_content('ACCAGTGTAG')
0.5
>>> gc_content('ATATATATA')
0.0
>>> gc_content('GCGGCCATGCATGGGG')
0.75
>>> gc_content('gcggCCATGcATGGGG')
0.75 # if you implement case-insensitivity as an optional challenge

Note that in Python, dividing two integers always returns a float, which is convenient in this function. [1]

Add a docstring to your function so that typing:

help(gc_content)

in the Python interpreter will print out a description of what the function does, what its (single) argument should be (including its type), and what its return value represents. Note that your docstring should specify to clients how case-sensitivity is handled as well.

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


1. If you really want division to return an integer, you have to use the // operator.