关键词 > CS-UY1113

CS-UY 1113 Problem Solving and Programming I — Spring 2024 Homework #7

发布时间:2024-06-01

Hello, dear friend, you can consult us at any time if you have any questions, add WeChat: daixieit

CS-UY 1113 Problem Solving and Programming I —  Spring 2024

Homework #7

Due: 10:00 pm, Monday, April 29, 2024

Submission instructions

1.  You should submit your  homework on Gradescope. To do so, turn in separate .py files for each question or question part, named according to the following pattern: hw7_q1.py,  hw7_q2.py, etc.

2.  Each Python file you submit MUST contain a header comment block as follows: # Author: INSERT YOUR NAME HERE

# Assignment / Part: HW7 - Q1 (etc.)

# Date due: 2023-04-29

# I pledge that I have completed this assignment without

# collaborating with anyone else (including using someone

# else's solution/partial solution, or sharing my

# solution/partial solution) in conformance with the

# NYU School of Engineering Policies and Procedures on

# Academic Misconduct.

Homework Rules

1.  All work should be your own. You should not use any other person's solutions or partial solutions  in your submission. This  includes, but is not limited to current and former students of this class, other Python-related classes, or other students at other institutions. The sharing of your solution or partial solution or work-in-progress is also a violation of the Code of Conduct. The use of generative AI systems (such as ChatGPT) is  forbidden. These rules have been  previously discussed in class. If you do not understand the limitations, please ask a professor. Violating these rules will be treated as a violation of the Tandon Student Code of Conduct.

2.   Do not use any Python language statements or features that have not been lectured on in class by a professor. You may encounter such statements / features / functions in your readings, prior experience, or self-learning. If we didn't cover it in lecture, it's not permitted. If you are unsure if we did or did not cover a topic, please post a question to the EdStem Discussion board .

3.   For this homework you can or will need to use the following:

basic input and output

expressions, variables, and assignments

conditionals (if/elif/else), includes the use of nested conditional statements

All things strings (iteration, indexing, string methods, string slicing, and formatting)

user-defined (programmer-authored) functions

loops (while / for), includes the use of nested loops

All things lists (includes 2D lists)

(iteration, indexing, list methods, list slicing and list comprehensions)

All things tuples (iteration, indexing, tuple methods, and tuple slicing)

Do not use any of the following language constructs (not an inclusive list): break, continue and pass statements, maps, sets, dictionaries, lambda statements, or any library that is not random or math. Do not use recursive programming techniques.

Background

The data driven news/reporting website fivethirtyeight (https://abcnews.go.com/538) has collected some interesting data over the years. Fortunately for us, they have released it to the public on Github (https://github.com/fivethirtyeight), a site for supporting version control of files for programming projects. This homework uses one such file of data, which was collected in support of their article According To Super Bowl Ads, Americans Love America, Animals And Sex.

This homework is a series of individual functions that you will create which will analyze and use the data from this article. The data  is contained  in a separate file, and since we have not learned how to read files in this class, we will provide you the code necessary to do so, such that once read in by your program, you can then use the data as a 2D list for your analysis.

How to read the data file

First, download the data file from the professor's NYU box account with the following address: https://nyu.box.com/s/o7uihrlyo87mzsbto88nl9uizwhjjqh7. You can do this with a web browser by following the link and then clicking on the download button in the upper right portion of the screen. The file can then be saved to a location on your computer.

Note that the data file must be named superbowl-ads.csv when you save it and you must place it in the same location (directory) on your computer where your homework file is being saved.   The code below will attempt to open the file in the same location as the Python code file you are writing, and the data file must be located there. Do not alter the code below that opens the file. If you can not get the file to open, please visit with a class assistant during office hours to work out any problems.

Code to read the data file

def read_data(filen):
data = []
with open(filen) as infile:
infile.readline()
# discard header line of input file
for line in infile:
# read line by line as a string
line_list = line.strip().split(',')
# split line into list elements
data.append(line_list) # append the list into the larger list
return data
def main():
try:
fname = 'superbowl-ads.csv'
superbowl_data = read_data(fname)
print("Data file:", fname, "successfully opened.")
print()
except Exception as exc:
print("Exception in program:", exc)
else:
# Define you functions above, and invoke them here in this
# else block!
if __name__ == "__main__":
main()

Once the file is successfully read, the superbowl_data variable in the main function will contain a 2D list of the data which will look something like this:

[['2018', 'Toyota', 'https://superbowl-ads.com/good-odds-toyota/',
'https://www.youtube.com/watch?v=zeBZvwYQ-hA', 'False', 'False', 'False', 'False', 'False',
'False', 'False'],
['2020', 'Bud Light', 'https://superbowl-ads.com/2020-bud-light-seltzer-inside-posts-brain/',
'https://www.youtube.com/watch?v=nbbp0VW7z8w', 'True', 'True', 'False', 'True', 'True', 'False',
'False'],
['2006', 'Bud Light', 'https://superbowl-ads.com/2006-bud-light-bear-attack/',
'https://www.youtube.com/watch?v=yk0MQD5YgV8', 'True', 'False', 'False', 'False', 'True', 'True',
'False'],
['2018', 'Hynudai', 'https://superbowl-ads.com/hope-detector-nfl-super-bowl-lii-hyundai/',
'https://www.youtube.com/watch?v=lNPccrGk77A', 'False', 'True', 'False', 'False', 'False',
'False', 'False'],
['2003', 'Bud Light', 'https://superbowl-ads.com/2003-bud-light-hermit-crab/',
'https://www.youtube.com/watch?v=ovQYgnXHooY', 'True', 'True', 'False', 'False', 'True', 'True',
'True'],
['2020', 'Toyota', 'https://superbowl-ads.com/2020-toyota-go-places-with-cobie-smulders/',
'https://www.youtube.com/watch?v=f34Ji70u3nk', 'True', 'True', 'False', 'True', 'True', 'True',
'False'],
['2020', 'Coca-Cola', 'https://superbowl-ads.com/2020-coca-cola-energy-show-up/',
'https://www.youtube.com/watch?v=-gAZRN3SCBw', 'True', 'False', 'False', 'True', 'False', 'True',
'False'],
['2020', 'Kia', 'https://superbowl-ads.com/2020-kia-tough-never-quits/',
'https://www.youtube.com/watch?v=lMs79UXam9A', 'False', 'False', 'False', 'True', 'False',
'False', 'False'], ...]]

We strongly suggest that you consider writing the initial solution so that it can successfully open and read from the file, and  print the resulting data list. Visually verify that the data is "loaded" into your program by doing so. Once it is printed, examine the first few lines of data. Note that each sublist of the main list contains information about an advertisement during a SuperBowl game.  Details of the advertisement are provided in each sublist, in the following sequence.

year of game show_product_quickly

brand ●    patriotic

superbowl_ads_dot_com_url celebrity

youtube_url danger

funny animals

●    use_sex

Details of each column are found  in the  README file on the  Git Hub  page for the dataset (https://github.com/fivethirtyeight/superbowl-ads?tab=readme-ov-file#super-bowl-ads).

For the remainder of  the homework, implement the functions required and produce any appropriate output as described. Unless otherwise stated, do not produce any output in any function, but return the desired result of the analysis.

Note that in all cases, the data read by the read_data function will need to be passed to each function you author so that the functions can operate and analyze the data. Additional function parameters may need to be sent as well, depending on the function's goal. Also note the data and return type that the function should return. Generally speaking you should be invoking the function in your main function one at a time, (after the else clause) and then print the result of the function.

Naming your solution file

All of your code (all functions and the Pythonic way to start the program) should be in the file hw7.py

Question 1 (10 points):

Write a function named get_num_pepsi_or_coke which calculates and returns the number of ads in the dataset that either Pepsi or Coca-Cola ran. That is, what is the number of ads in which the brand is either 'Pepsi' or 'Coca-Cola'. Return an integer value that is 0 or greater. The function should print nothing. Do not use a list comprehension to compute the answer. You will be re-implementing this function below with a list comprehension.

Once the function is invoked and returns, the program should print the result as follows. Include the Q-number and the text exactly as:

Q1: The number of Pepsi or Coca-Cola advertisements was: XXX (where XXX is the value returned)

Question 2 (15 points):

Write a function named get_num_doritos_listcomp that does the exact same thing as Question 1, however, rather than Pepsi and/or Coca-Cola, search for Doritos. Your implementation must use a list comprehension to compute the result.

Once the function is invoked and returns, the program should print the result as follows. Include the Q-number and the text exactly as:

Q2: The number of Doritos advertisements was: (where XXX is the value returned)

Question 3 (25 points):

Write a function named get_advertisers_for_year that returns an ascending sorted list of advertisers for a given year. The function should accept an integer year (e.g. 2010). The function will return a list of the brand (advertisers) that ran SuperBowl ads during the specified year. Each brand should be listed only once and the list should be in ascending alphabetical order.

Once the function is invoked and returns, the program should print the result as follows. Include the Q-number, the year, and the text exactly as shown. For example, if we invoke the function and pass it the year 2010, the result should be as follows.

Q3: Advertisers for 2010:

Bud Light

Budweiser

Doritos

E-Trade

Hynudai

Kia

NFL

Question 4 (25 points):

Write a function named get_advertiser_count_by_year which calculates and returns a list of sorted tuples.   Each tuple is a pair of an integer year, and the integer number of advertisers that ran an advertisement during the game that year.  (E.g. there were 8 ads run in 2008 according to our data source.) There should be only one tuple for each year in the data set and the tuples should be sorted (ascending) by the year value.

Once the function is invoked and returns, the program should print the result as follows. Include the Q-number, the year, and the text exactly as shown.

Q4: Advertisers by year, tuples of years and count, sorted ascending by year:

[(2000, 8), (2001, 13), (2002, 10), (2003, 12), (2004, 11), (2005, 8), (2006, 7), (2007, 14), (2008, 13),

(2009, 15), (2010, 14), (2011, 9), (2012, 15), (2013, 15), (2014, 14), (2015, 10), (2016, 13), (2017, 5),

(2018, 14), (2019, 15), (2020, 9)]

Question 5 (25 points):

Write a function named get_years_links_and_animals_by_advertiser_when_patriotic which returns a list of tuples of selected data for brands that have run patriotic advertisements (in any year). The each tuple in the list must contain the following information:

the year as an integer,

the YouTube link to the video as a string, and

●    if the advertisement used animals (True or False) as a boolean

This solution must  use a list comprehension to do all of the work (iteration, filtering, sublist construction, data conversion). The function literally can be written in one line (two at the most) using a robust list comprehension to build the results and then return the results.

The function should be used 2x once for the advertiser E-Trade and once for Busweiser. Each time the function is invoked and returns, the program should print the result as follows. Include the Q-number, the year, and the text exactly as shown.

Q5a: Years, links, and animals for a given advertiser (E-Trade):
[[2007, 'https://www.youtube.com/watch?v=jaR5-kefxn4', True], [2018,
'https://www.youtube.com/watch?v=Qx5-AZlfjp4', True]]
Q5b: Years, links, and animals for a given advertiser (Budweiser):
[[2020, 'https://www.youtube.com/watch?v=J0xugdotpp8', True], [2002,
'https://www.youtube.com/watch?v=1MZUvib98Rs', True], [2009,
'https://www.youtube.com/watch?v=ukpnHh4eEeQ', True], [2009,
'https://www.youtube.com/watch?v=w_ZEGUX4YnI', True], [2004,
'https://www.youtube.com/watch?v=pmmsr7PAhWU', True], [2015,
'https://www.youtube.com/watch?v=7_EfXuGev24', True], [2017,
'https://www.youtube.com/watch?v=HtBZvl7dIu4', True], [2008,
'https://www.youtube.com/watch?v=odpagg0jV6I', True], [2014,
'https://www.youtube.com/watch?v=XxfxB0O9Uuk', True], [2018,
'https://www.youtube.com/watch?v=GNVw5f16GEM', True], [2016,
'https://www.youtube.com/watch?v=to4dhysGYD0', True], [2012,
'https://www.youtube.com/watch?v=TieDNumMwOc', True], [2010,
'https://www.youtube.com/watch?v=IQHlA9qKJv4', True], [2015,
'https://www.youtube.com/watch?v=otCxSnu_HXA', True], [2014,
'https://www.youtube.com/watch?v=gUGGepL5gGU', True], [2012,
'https://www.youtube.com/watch?v=_GeiOdHsW_8', True]]