Working on Programming Assignments
This page contains general advice for working on programming assignments in my courses.
Tips for Working on Assignments
Work from the top-level directory. Instructions assume you are in the directory you checked out, which contains the
README.mdandpyproject.toml. While some commands may work from other directories, staying in this top-level directory will avoid lots of issues.Read the instructions carefully. The
README.mdfile contains the instructions. Make sure you understand what you’re being asked to do before you start writing code. If you’re not sure, ask for clarification on Ed.Check in often. As you work, check your code into git and push to GitHub regularly. This will help you avoid losing work if something goes wrong with your machine.
Run the tests. The tests are there to help you. If you’re not sure if your code is correct, run the tests and see if they pass as a first step. If they don’t, read the error messages carefully, they should give you a place to start investigating.
Experiment in the REPL. If you’re not sure how a particular function or method works, try it out in the REPL (
uv run python3oruv run ipython). A major advantage of interpreted languages is this ability to experiment interactively.Ask questions of course staff - If anything is not clear, ask questions via Ed! If you are stuck or need help with a concept, office hours may be a good idea as well!
Use a linter.
ruffwill be introduced in this class. Using it (or a linter of your choice) in this course will let you focus on the actual problem, help you write cleaner code, and detect common issues that may result in a lower grade.Learn
pytestshortcuts - You’ll be spending a lot of time with it, so learn how to use the command line flags.
Getting Help
It is expected that most students will need help outside of class in some manner. It is important to engage with the course staff beyond just attending lecture to get the most out of this class.
The two primary means of this are Ed Discussion and Office Hours. They serve related, but distinct purposes— here’s how to get the most out of each of them.
Office Hours
Office Hours are regular time that TAs and I set aside for you to get help on concepts and assignments.
You can come by at any point during this period and we’ll do our best to answer your question. Please come with your laptop, and questions prepared ahead of time, as sometimes there will be a line and it’s important we make time for everyone.
Ed Discussion
Ed Discussion is a forum that you may use to ask questions that can be answered by course staff and your fellow peers.
Asking technical questions is an important skill in and of itself, you’ll be asking your colleagues and friends technical questions in your job, and it is good to get practice at this here.
Below is some general advice on how to approach Ed:
Search Before Asking
Before posting a question on Ed, check whether it has already been answered in a previous post. For example, suppose you are getting an IndexError; you could search just for that word to see if any other students have encountered that same error (and, if you’re lucky, an instructor/TA will have already answered it).
Make sure to always check the “pinned” posts. We will often “pin” a post about a particular assignment that might contain the information you are looking for. Be sure to read these first.
Ask A Question
Make sure you’re going to ask an actual question. You need to tell us about a specific issue you’re encountering, and why you’re stuck on it (e.g., you are not getting the expected result, the tests are failing in a way you do not understand, etc.). Writing a post that says “I can’t get Task 4 to work, I have pushed my code. Please look at it.” is not a question.
It may be helpful to write your question in the format of “I did {X}, expecting {Y}, but {Z} happened instead.” This can help us understand the source of the error and reduce the time it takes to get you a high quality answer.
Public vs. Private
All questions about coursework, course logistics, etc. should be asked publicly (please note that you do have the option of asking the question anonymously if you prefer). If you ask such a question privately, we will not answer it: we will ask you to ask it publicly, and will answer it once you do. This way, everyone can benefit from the answer to the question and, if someone runs into the same issue you do, we can refer them to the answer we provided in your post.
The more information, the better!
Sometimes people are brief to avoid wasting people’s time. With code, the opposite is usually true — the more information you provide the more easily we can solve your problem.
In particular, it will be much easier for us to help you if we are able to reproduce the exact issue you are encountering (i.e., when we run your code, we must be able to observe the exact same issue you’re encountering). And to do so, we need as much information as possible from you:
If your question relates to your code, make sure you push your code to GitHub before asking for help.
Make sure you’re running your code on a CS machine. We will not be able to provide assistance if you are running your code on your personal machine, as this will make it harder for us to reproduce the exact issue you are encountering.
Include a detailed description of the exact chain of events that lead to the issue you’re encountering (Are you testing a specific function? If so, with what inputs? Does the issue come up when you run a test? Etc.).
If you encounter an error message (or any other unexpected output) when running a command (like a Python program, pytest, or git) or when testing a piece of code in the interpreter, please make sure you include the full and unabridged error message (or unexpected output). Summarizing the message (e.g., “Python says something about a KeyError”) makes it harder for us to figure out what the issue is.
If something is “wrong”, please describe in what way it seems wrong to you. For example, were you expecting a particular output but got a different one? Is a piece of code behaving in a way you were not expecting? Etc. It can be useful to tell us what you were expecting the code to do, and what you encountered instead.
No Code / No Screenshots
Never post your code in Ed. As noted in our Academic Honesty policies, you should never share your code with other students, which means you should never post it on Ed. If you need us to look at your code, just push it to the Git server and we will look at it there. Please note that, if a test prints out a few lines of code as part of its output, that’s OK.
No screenshots. Do not post screenshots of the output. Screenshots are not searchable, and may pose readability issues for some people. Instructors/TAs may also want to copy-paste that output somewhere else, which is not possible if you post a screenshot.
If you need to share some output with us, copy-paste from the terminal onto Ed, and use Ed’s “code block” formatting. To copy something on the terminal, just select it (the same way you would do in a word processor: click, and then drag until the end of the output) and press Control-Shift-C.
Other Ed Discussion Tips
Avoid posts that have multiple unrelated questions.
Instead, write a separate post for each question. Please note that it is OK to ask multiple questions in one post if they all relate to the same issue.
When to use follow-ups and when to post a new question.
If you need to provide additional information (say, because we pointed you to this page), please use a follow-up in the same thread. If, on the other hand, you have an entirely new question, please write a new post for it. That way, if others have that same question, it will be easier for them to find your post (and our answer to it), instead of having to dig through the followup discussions of unrelated posts. Do not edit the original question: it is unlikely that we will notice your change.
Found the answer yourself?
If you solved your problem before we got around to helping you, please note that the issue is resolved. If the solution is not specific to your implementation, please add a brief explanation of how you solved the problem in case anyone else runs into the same issue.
Grading
We use a form of specifications grading for this course, each programming assignment is worth 5 points:
- Completion (2 points) - Completion is usually judged based on a number of tests that need to be passed for full credit. Some assignments may have additional completion criteria.
- Efficiency (2 points) - Is the code reasonably efficient, given the general criteria covered in this class? This may also involve meeting any specific requirements made in the assignment.
- Code Quality (1 point) - How well does the code adheres to the style guide and other quality standards outlined in the grading specification?
Below, this page explains some of the common deductions for Efficiency and Code Quality. This is not an exhaustive list, other penalties may be applied for assignment-specific restrictions, solutions that bypass the point of the assignment, etc. These will often be noted in the assignment write-up, but it is impossible to enumerate every potential deduction.
Code Quality
Code is read much more often than it is written.
Producing code that solves a problem is only part of the task, that code needs to be intelligible to your fellow developer and/or future self. Hard to understand & overly complex code is source of subtle bugs.
Each assignment will be evaluated for the presence of common code quality issues.
CQ: Banned Constructs (-1)
Some Python features are considered bad practice in production code.
While you will see these in examples, most projects & teams prohibit their use.
Banned Constructs:
- use of a bare
exceptorexcept Exceptionstatement - use of
import *is explicitly banned in this class
Examples:
from modA import *
from modB import *
# The origin of symbols used in this file are not clear.
# In fact, reordering the imports or changes to either
# could result in the code breaking if the two modules
# define the same.# INCORRECT: this code incorrectly catches the NameError
try:
func(this_variabl_has_typos)
except:
...
# CORRECT: this only catches ValueError, so if func raises
# that error it is correctly handled
try:
func(this_variabl_has_typos)
except ValueError:
...CQ: Incomplete (-1)
An assignment that is missing significant portions will have this penalty applied in addition to any present in the code.
CQ: Function Decomposition (-0.5)
- The presence of copy/pasted code where it would be more appropriate to use a helper function.
- One large function that does many things instead of smaller functions.
CQ: Non-idiomatic (Unpythonic) Code (-0.5)
Code that does not use Python’s features correctly.
Example:
# INCORRECT: this code obtains an integer only to index back into
for i in range(len(items)):
print(items[i])
# CORRECT: use direct iteration, or enumerate
for item in items:
print(item)
for idx, item in enumerate(items):
print(idx, item)CQ: Hard to Read (-0.5)
Not following other general formatting guidelines that aim to increase readability.
- Improper indentation.
- Code consistently exceeding line length.
- Improper use of blank lines per style guide.
- Debugging statements left in (
print,breakpoint, etc.). - Use of “magic numbers” or strings where constants would be appropriate.
CQ: Variable Names (-0.5)
- Variable names should be meaningful & aid in understanding of the code.
- Avoid using single letter names (other than in common contexts like i/j to loop over integers).
CQ: Commenting (-0.5)
Comments should enhance understanding of the code.
- Code that is significantly under-commented. (Complex sections with no explanation at all.)
- Code that is significantly over-commented, meaning code that describes “how” instead of “why”.
- Missing docstrings on multiple functions.
Efficiency
EF: Duplicated Data (-0.5)
Duplicating data in unnecessary ways, such as copying a list to a tuple for no reason.
# INCORRECT: creates three copies of the list of words
def get_unique_words(text):
words = text.split()
lowercase_words = [word.lower() for word in words] # copy 1
cleaned_words = [word.strip('.,!?') for word in lowercase_words] # copy 2
unique_words = set(cleaned_words) # copy 3
return unique_words
# CORRECT: only a single copy
def get_unique_words_efficient(text):
unique_words = set()
for word in text.split():
unique_words.add(word.lower().strip('.,!?'))
return unique_wordsOr a more signficant example:
# CORRECT
for item in csv.DictReader(fd):
process_data(item)
# INCORRECT: creates an entire second copy of the data
# despite there only being a need to access one at a time
items = list(csv.DictReader(fd))
for item in items:
process_data(item)EF: Redundant Work (-0.5)
Doing redundant work, like going through a list twice when a single pass would have sufficed.
This can be thought of as “too many loops”, looping three or more times when one would do.
Or in terms of complexity, this can be thought of as turning an O(N) into an O(2N) or similar.
Example:
# INCORRECT: this code iterates through the data twice
count_positive = sum(1 for x in data if x > 0)
count_negative = sum(1 for x in data if x < 0)
# CORRECT: this code iterates once
count_negative = 0
count_positive = 0
for x in data:
if x < 0:
count_negative += 1
elif x > 0:
count_positive += 1EF: Reimplemented built-ins (-0.5)
It is almost always more efficient to use the built-in functions in the language over implementing logic yourself.
Common examples:
- iterating through a string/list to find a single element instead of
container.find(item)or similar - Combining lots of strings using
+instead of.joinor f-strings.
EF: Other Minor Efficiency Issue (-0.5)
Small issues that lead to code being slower/less efficient than it should be.
Common examples:
- Incorrect data structure (e.g. using a list to keep unique items instead of a set)
- Repeatedly calling a function inside a loop with the same arguments, should be moved outside the loop.
EF: Major Complexity Error (-1)
This penalty applies to solutions where a drastically more efficient solution exists.
This can be because of unnecessary looping/recursion or an incorrect data structure (e.g. searching a list for items when a dictionary would have given O(1) lookup)
In terms of complexity this might mean:
- O(1) into O(N)
- O(N) into O(N^2)
Example:
# INCORRECT: O(N^2) implementation that needs a nested for loop
def find_duplicates_quadratic(lst):
duplicates = []
for i in range(len(lst)):
for j in range(i + 1, len(lst)):
if lst[i] == lst[j] and lst[i] not in duplicates:
duplicates.append(lst[i])
return duplicates
# CORRECT: O(N) implementation that uses a set appropriately
def find_duplicates_linear(lst):
seen = set()
duplicates = set()
for item in lst:
if item in seen:
duplicates.add(item)
seen.add(item)
return duplicates