Assignment 4
Tackle as many of these problems as you can, submitting your answers along the way via this Google Form, which should autosave your answers. Be sure to click SUBMIT at the bottom of the Google Form when you have completed the assignment. You should receive an email receipt when the form has been properly submitted. You can resubmit, too, as many times as you’d like before the assignment’s deadline. Refer to these instructions for guidance on submitting.
Please be mindful of the course’s policy on academic honesty as you complete this assignment. When you engage with others regarding this assignment in peer learning sessions, be aware of our guidelines for assignment-related discussions. With the above in mind, the solution for the first item below denoted with an asterisk (*) may be openly discussed without restriction during peer learning sessions.
Not to worry if you run into trouble. Do just attend office hours for help! Further, consult our AI-based tool, cs50.ai.
Like last week, you’ll want to log into cs50.dev using your GitHub account in order to use Visual Studio Code (VS Code) in the cloud. No need to install anything on your own computer. Keep in mind that you can create or open a file (e.g., hello.py
) by typing
code hello.py
in VS Code’s terminal window. And you can run a program (e.g., hello.py
) by typing
python hello.py
in VS Code’s terminal window.
Question 1*
Strings
Suppose a program contains the declaration:
s = "Python rocks?"
Now evaluate each of the following independent expressions. If you can’t remember how some of these String methods work, try looking at the documentation at Python String Methods or W3Schools Python String Methods.
A. s.count (“o”)
B. s[-2].islower()
C. s[2:20]
D. "Yt" in s
E. s.find("o")
F. s.replace ("ck", "foobar")
Question 2
Lists
Part 1
What are the contents of the names variable after the following code has been executed?
names = ["Ramon"]
names.insert(1, "David")
names.insert(0, "Henry")
names.append ("Rodrigo")
names.pop(3)
names.append("Henry")
Part 2
Suppose a non-empty Python list of integers named revenue has been created. Write one or more Python statements to perform each of the following. Note that each task is independent of the others:
A. Set every element of revenue to the value 5.
B. Shift all elements by one to the right and move the last element into the first position. For example, [1, 4, 9, 16, 25]
would be transformed into [25, 1, 4, 9, 16]
.
C. “Swap” the first value in the revenue list with the last value in the list.
D. Change all negative values to positive values (of the same magnitude) in revenue.
Question 3
Files and Command Line Arguments
Suppose we have a text file named stockPrice.txt containing the closing price of a stock on a number of consecutive days. The file contains a single float value on each line and might appear something like this:
16.20
23.50
19.15
7.40
22.80
18.50
1.80
4.90
Shown below is an almost complete program that will read one line at a time from a file such as this, and output the difference in stock price from one day to the next:
# This is file stocks.py
from sys import argv
def main():
if len(argv) != 2:
print('Sorry, correct usage is: python stocks.py input-file')
return
input_file = # missing expression goes here
previous = float (input_file.readline())
# assume the file has at least one value in it
for line in input_file:
next = float(line)
# missing print statement goes here, using an f-string for formatting
# missing assignment statement goes here
main()
When the complete program is executed, the output should look like this:
$ python stocks.py stockPrice.txt
$16.20 to $23.50, change = $7.30
$23.50 to $19.15, change = $-4.35
$19.15 to $7.40, change = $-11.75
$7.40 to $22.80, change = $15.40
$22.80 to $18.50, change = $-4.30
$18.50 to $1.80, change = $-16.70
$1.80 to $4.90, change = $3.10
You should supply the missing expression and the two missing Python statements (one is a print statement, the other an assignment statement) to make the program work as shown.
Question 4
Dictionaries
Define a dictionary that maps month numbers (1 through 12) to month names (January, February, etc.). Month numbers are the “keys”.
Question 5
Processing CSV Files (using DictReader)
Consider (again) this table of employees, a copy of which can be found here: employees.csv.
Create a blank csv file, named employees.csv
, in your text editor, and copy-and-paste the contents of the csv file above into your own newly created employees.csv
file. Then, create a python file, named employees.py
, also in your text editor, to implement a program that whittles employees.csv
down to just three fields by:
- opening
employees.csv
for reading, - printing, verbatim,
Manager,LastName,FirstName
, on a line of its own, and - printing, for each employee in employees.csv, on a line of its own, the employee’s manager, followed by a comma, the employee’s last name, followed by a comma, and the employee’s first name.
Your program should thus output:
Manager,LastName,FirstName
,Adams,Andrew
Michael Mitchell,Callahan,Laura
Andrew Adams,Edwards,Nancy
Nancy Edwards,Johnson,Steve
Michael Mitchell,King,Robert
Andrew Adams,Mitchell,Michael
Nancy Edwards,Park,Margaret
Nancy Edwards,Peacock,Jane
Notice the leading comma for Andrew Adams, who doesn’t have a manager.
Each name that you print should be extracted from employees.csv
; no names should be hard-coded into your program.
Let’s now assign each employee a unique identifier, an integer starting at 1
that’s incremented for each employee in employees.csv
, from top to bottom.
Modify employees.py
in such a way that the program
- outputs, verbatim,
Id,Manager,LastName,FirstName
, on a line of its own, and - outputs, for each employee, on a line of its own, a unique identifier for the employee, followed by a comma, followed by the employee’s manager, followed by a comma, followed by the employee’s last name, followed by a comma, followed by the employee’s first name.
Your program should thus output:
Id,Manager,LastName,FirstName
1,,Adams,Andrew
2,Michael Mitchell,Callahan,Laura
3,Andrew Adams,Edwards,Nancy
4,Nancy Edwards,Johnson,Steve
5,Michael Mitchell,King,Robert
6,Andrew Adams,Mitchell,Michael
7,Nancy Edwards,Park,Margaret
8,Nancy Edwards,Peacock,Jane
Notice the pair of adjacent commas for Andrew Adams, who doesn’t have a manager.
Each name that you print should again be extracted from employees.csv
; no names should be hard-coded into your program.
Let’s now eliminate the redundancy of storing managers’ names and instead associate with each employee the unique identifier of his or her manager.
Modify employees.py
in such a way that the program
- outputs, verbatim,
Id,ManagerId,LastName,FirstName
, instead ofId,Manager,LastName,FirstName
, on a line of its own, and - outputs, for each employee in
employees.csv
, the unique identifier of the employee, followed by a comma, the unique identifier of the employee’s manager, followed by a comma, the employee’s last name, followed by a comma, and the employee’s first name.
Your program should thus output:
Id,ManagerId,LastName,FirstName
1,,Adams,Andrew
2,6,Callahan,Laura
3,1,Edwards,Nancy
4,3,Johnson,Steve
5,6,King,Robert
6,1,Mitchell,Michael
7,3,Park,Margaret
8,3,Peacock,Jane
Notice the pair of adjacent commas for Andrew Adams, who doesn’t have a manager.
Each name that you print should again be extracted from employees.csv
; no names should be hard-coded into your program.
Hints
If an employee’s first name is in a variable, FirstName
, and an employee’s last name is in a variable, LastName
, recall that you can concatenate them in a variable, Name
, with code like:
Name = f"{FirstName} {LastName}"
Or:
Name = FirstName + " " + LastName.
And recall that you can compare two variables, a
and b
, for equality with code like:
if a == b:
More Hints
Recall that a dict
(i.e., dictionary) in Python allows you to associate “keys” with “values.” Accordingly, you can use it to “look up” values by keys, much like you can look up definitions (in a real-world dictionary) by words.
For instance, suppose that you’d like to associate humans with their favorite numbers. You could instantiate (i.e., create) an initially empty dict
for such as follows:
favorites = {}
And you could then add some keys and values as follows:
favorites["Freddy"] = 13
favorites["Douglas"] = 42
Thereafter, to check if someone’s favorite number is, say, 50, you could use code like the below, where someone
is their actual name:
if favorites["someone"] == 50:
Question 6
Retrieving Web Data and APIs
According to the documentation for Alpha Vantage’s TIME_SERIES_DAILY API, via what URL could you get a CSV file with the daily close prices of IBM’s stock since 2000? Assume that your API key is “demo”, even though the URL won’t work with that key.
Sign up for a free API key for Alpha Vantage. Be sure to copy/paste it somewhere safe!
Then solve this problem:
Recall that Alpha Vantage offers a TIME_SERIES_DAILY API, which allows you to get a CSV file with the daily close prices of a stock from the past 20+ years.
Create a python file, named prices.py
, in your text editor, to implement a program that
- prompts the user for a stock symbol (via the command line) and
- outputs, line by line, a date followed by the close price of that stock on that date.
If the user inputs MSFT
, your output should resemble:
2019-04-22 $123.7600
2019-04-18 $123.3700
2019-04-17 $121.7700
...
1998-01-06 $131.1300
1998-01-05 $130.3800
1998-01-02 $131.1300
Your first line of output, though, should be for the date on which the market most recently closed.
Hint
Assuming your program has a variable called API_KEY
, you can run (and thus test) your program by running it with a command like
API_KEY=YOURS python3 prices.py MSFT
but replace YOURS
with your own API key.
Question 7
Sets
Consider the set definitions below and then answer a series of questions:
set1 = {1, 2, 3, 4, 5}
set2 = {2, 4, 6, 8}
set3 = {1, 5, 9, 13, 17}
A. Is set1
a subset of set2
?
B. Is the intersection of set1
and set3
empty?
C. What is the result of performing set union on set1
and set2
?
D. What is the result of performing set intersection on set2
and set3
?
E. What is the result of performing the set difference on set1
and set2
? In other words, (set1 – set2)
?\
Question 8
Waterfall vs. Agile
Read Robert Austin’s case on Methodology Wars in Software Development to get a better sense of waterfall and agile. In what contexts might a waterfall methodology be better than agile? In what contexts might an agile methodology be better than waterfall?
Question 9
Thinking Deeper about Waterfall vs. Agile
How do the differences between these two approaches reflect underlying philosophical beliefs about the best way to manage complex software development projects?
Question 10
CMM vs. Agile
Further skimming Robert Austin’s case on CMM versus Agile, get a sense of disparate software-development methodologies in industry and make some very short notes for later (potential) discussion.