Python
Homework 3
● Note: Plagiarism is serious.
○ This work should be finished independently. Please do not discuss with each other.
○ Getting help from googling or reading books are encouraged for the scope of this homework.
● Submission
○ For each problem below, submit file(s) electronically to Blackboard according to description.
Objective
● string: split(), strip(), \n, form new string by concatenation, string formatting
● list: list comprehension, looping, indexing, slicing
● list & string sorting
● enumerate: built-in function, a very useful way to do looping
(enumerate: advanced, only included in homework, not included in exams)
● matplotlib: advanced for now, good to start trying it …
Grading Guideline
● Your code should execute. For code with errors executing, points will be deducted.
● Keep code clean, unclean code will get points deducted.
Unused lines of code or debugging prints should be removed before submitting. Repeated lines or functionalities
should be avoided. You may lose points if code has repeating lines. (for example, you may calculated “prices”
already, but later you calculated it again, is considered repeating code)
● Variable Naming: use variable names that make sense, avoid built-in and reserved keywords.
Problem1: Python List and String
Description
Download ‘string_and_list__stock_price.ipynb’ from Blackboard. This file will serve as a “code example” that will help us
finish the homework required below. Go through all the steps on Jupyter Notebook, including the one marked as
‘advanced’. Self learning is a good skill when it comes to programming. For steps that seem hard to understand, feel
free to try the code snippet in a new Jupyter Notebook file, or in Python shell. Also, google is a good way to learn. 🙂
1. Use code snippets given, write a function called “def top_prices(prices, n):”, which will take in 2 arguments. First
argument is the list of prices, each price should be of a number type(int or float). Second argument ‘n’ indicates
top n prices. For example, if n=3, this function should return a new list of the top 3 prices, sorted from low to
high. If n=10, this function should return a new list of the top 10 prices, sorted from low to high.
a. This function should not change the original ‘prices’ passed in.
b. This function should return a list, it should not print anything.
For debugging purposes, at first we can add printing statements inside, but before submitting please
remove all prints. If things don’t work at first, try PyCharm Debugger (youtube has a lot of tutorials).
def top_prices(prices, n):
B = sorted(prices)
B = b[-n:]
Return b
2. Use code snippets given, write a function called “def first_20_stock_prices(symbols, prices)”, which will take 2
input arguments, ‘symbols’ and ‘prices’. Prices is list of prices in float. Write a ‘for’ loop, to print to screen both
stock symbols and stock prices, for first 20 stocks, in user friendly way. One example line from print:
“Symbols: GE, Stock Price: 16.13”
a. Each symbol and price for this symbol must be on the same line.
b. Price should only keep 2 decimal places, like 16.13.
c. This function should only print, should not return anything.
For i in range(20):
print(“symbols: %s, \t Stock price: %.2f” % (symbol[i], price_list[i]) )
3. Use code snippets given, write a function “def top_quartile_prices(prices):”, which will take in original ‘prices’ in
list of floats, and will print the top quartile prices, in other words, should print the top 25% of the prices, sorted
from high to low. It should only care about prices, not symbols. A user friendly message should be printed,
example: “The top quartile prices are: 100.1, 99.2, 98.3…..”, with 1 decimal place for numbers. Note 100.1 is
only an example, the real top prices may be different. This function should only print, it should not return
anything. For more information on what ‘quartile’ means, please google.
prices_list.sort( reverse = True)
Quartile = len(price_list) // 4 (always rounds down)
print(“the top quartile prices are:”,prices_list[0:quartile])
4. Use code snippet given, write a function “def visualize(prices):”, which will do the same thing as in Jupyter
Notebook. You can just copy / paste the examples, or if you want to do some tweaks to the x/y axis, or x/y ticks,
or title on top, you’re welcome to do so. Exact copy of the given code will get full score for this step. The purpose
of this step is mostly about making plot work on your computer.
Put 6 in the function,
5. Write a function called ‘def main()’, that takes in no argument. This ‘main’ will initiate some data, manipulate data
to the format we like, then call the 4 functions described above.
a. Initiate the original ‘prices’ and ‘symbols’ in main, starting from ‘prices_str’ in the first line and
‘symbols_str’ in the first few lines in the Jupyter Notebook. Do some data manipulation until you get a list
of floats, as ‘prices’ and list of strings as ‘symbols’, without space or “\n” (new line characters) in symbols.
b. In ‘main’, call ‘top_prices(prices, n)’ twice, using n=5 and n=20 respectively, assign the return value to a
variable each time, then write a line to print user friendly message, something like ‘Top 5 stock prices are
[5, 6, 7….]’. This is just an example. Please use str.format() formatting for n=5, and f-string formatting for
n=20.
c. In ‘main’, call function ‘first_20_stock_prices(symbols, prices)’. The function itself will print to screen, so we
don’t have to print anything for this function inside of ‘main’.
d. In ‘main’, call function ‘top_quartile_prices(prices)’, which will print the result inside of function.
e. In ‘main’, call function ‘visualize(prices)’, which should draw a graph similar to the one in Jupyter
Notebook. If your computer won’t make any plot, google and try to fix it, or email me.
Def main():
#a.
All that code in the jupyter notebook
#b.
T5 = top_prices(prices, 5)
T20 = top_prices(prices, 20)
print(“Top 5 stock prices are {}”.format(T5))
print(f”Top 20 stock prices are {T20}”)
#c.
first_20_stock_prices(symbols, prices)
#d.
top_quartile_prices(prices)
#e.
visualize(prices)
6. Submit python file “stock_yourlastname.py” to Blackboard. Please substitute your last name in file name.
Problem 2: List Comprehension
You’ll be given a file list_comprehension.py, please follow instruction in the file, to fill in the missing code blocks.
Please rename the file as list_comprehension_yourlastname.py and submit it.
Objective
● list comprehension
● if statement
Problem 3: Date Checker
Objective
● loop using range()
● string split, formatted output
● flow control: if statement, maybe need to use ‘else’ or ‘elif’ too.
Description
Write a program using a function, call it I date_checker_yourlastname.py, it will ask the user to input a date string,
and use a loop to ask the user to input for 5 times total. This program should tell if a date is valid or not valid, and output
to screen.
● Note each month may not have the same amount of days, like: Jan has 31 days, Feb has 28 days.
● For simplicity, let’s not worry about leap year, and assume February always has 28 days.
● Day should not be <=0 or >max days of that month. Months should be within 1-12. Year should be positive.
Def date_checker:
# example output
$ python3 date_checker.py
This program accepts a date in the form month/day/year and outputs whether or not the date is valid
Please enter a date (mm/dd/yyyy): 03/31/2000
03/31/2000 is valid
Please enter a date (mm/dd/yyyy): 01/32/2017
01/32/2017 is not valid
Please enter a date (mm/dd/yyyy): 00/20/1997
00/20/1997 is not valid
Please enter a date (mm/dd/yyyy): 05/38/2010
05/38/2010 is not valid
Please enter a date (mm/dd/yyyy): 13/00/2018
13/00/2018 is not valid