· 6 years ago · Mar 29, 2019, 05:54 PM
1Through the end of Module 3.
2
3
4# Write a f(x) that takes a string as a parameter representing
5# the name of a file to read and returns the number of lines in the file.
6
7
8def count_lines(f):
9 list = []
10 with open(f, "r") as file:
11 for line in file:
12 line = line.rstrip('\r\n')
13 list.append(line)
14 return len(list)
15
16
17# Write a f(x) that takes no parameters and returns a list of strings.
18# The function will read a file named "commonly.txt" and returns the contents
19# of the file in an array with each line of the file as a separate values
20# in the data structure.
21
22
23def file_to_list():
24 list = []
25 with open("commonly.txt", "r") as file:
26 for line in file:
27 line = line.rstrip('\r\n')
28 list.append(line)
29 return list
30
31
32print(file_to_list())
33
34
35# Define a f(x) that takes no parameters and returns an integer. The function
36# will read a file named "web.txt" that contains one a well-formed integer one
37# each line. This function should return the average of all these integers.
38
39# *Don't know if the following code is correct:
40def average_ints():
41 list = []
42 sum = 0
43 with open("segment.txt", "r") as file:
44 for line in file:
45 line = line.rstrip('\r\n')
46 list.append(int(line))
47 for index in list:
48 sum = sum + index
49 return sum / len(list)
50
51
52# Write a f(x) that takes no parameters and returns an integer. The function
53# will read a file named "legislation.txt" that contains one a well-formed
54# integer one each line. This function should return the sum of all these
55# integers.
56
57def sum_ints():
58 list = []
59 with open("legislation.txt", "r") as file:
60 for line in file:
61 line = line.rstrip('\r\n')
62 list.append(int(line))
63 return sum(list)
64
65
66# Write a function named "file_to_int_list" that takes no parameters
67# and returns a list of integers. The function will read a file named
68# "radar.txt" and returns the contents of the file in an array with each
69# line of the file as a separate values in the data structure. You must
70# convert each line to an integer and you can assume each line is a
71# well-formed integer.
72
73
74def file_to_int_list():
75 list = []
76 with open("radar.txt", "r") as file:
77 for line in file:
78 line = line.rstrip('\r\n')
79 list.append(int(line))
80 return list
81
82
83# Write a f(x) called csv_to_list that take a string as a parameter
84# representing the name of a CSV file with 5 columns in the format
85# "<int>, <int>, <int>, <int>, <int>" and returns a new list containing all
86# all the values in the fourth column as integers in the same order they
87# appear in the input file.
88
89
90import csv
91
92
93def csv_to_list(file):
94 list = []
95 with open(file, newline="") as f:
96 reader = csv.reader(f)
97 for line in reader:
98 list.append(int(line[1]))
99 return list
100
101# Create a f(x) that takes a string as a parameter representing the name of
102# a CSV file with 5 columns in the format "<int>,<int>,<int>,<int>,<int>"
103# and returns the average of all the values in the third column from the input
104# file.
105
106
107def csv_average(file):
108 list = []
109 sum = 0
110 with open(file, newline="") as f:
111 reader = csv.reader(f)
112 for line in reader:
113 list.append(int(line[2]))
114 for index in list:
115 sum = sum + index
116 return sum / len(list)
117
118
119# Create a f(x) that takes a string as a parameter representing the name of
120# a CSV file with 5 columns in the format "<int>,<int>,<int>,<int>,<int>"
121# and returns the sum of all the values in the third column from the input
122# file.
123
124
125def csv_sum(file):
126 list = []
127 sum = 0
128 with open(file, newline="") as f:
129 reader = csv.reader(f)
130 for line in reader:
131 list.append(int(line[2]))
132 for index in list:
133 sum = sum + index
134 return sum
135
136
137# Write a f(x) that takes a string as a parameter representing
138# the name of a CSV file with 4 columns in the format
139# "<string>,<float>,<float>,<float>" and returns a new key-value store
140# mapping strings to floating point numbers. The returned key-value
141# store will have one pair for each row in the file with keys from the
142# first column of the CSV file and values from the second column.
143
144
145def csv_to_kvs(file):
146 dict = {}
147 with open(file, newline="") as f:
148 reader = csv.reader(f)
149 for line in reader:
150 keys = line[0]
151 values = float(line[1])
152 dict[keys] = values
153 return dict
154
155
156# You have a CSV file of individual song ratings and you'd like to know
157# the average rating for a particular song. The file will contain a single
158# 1-5 rating for a song per line.Write a f(x) that takes two strings as
159# parameters where the first string represents the name of a CSV file
160# containing song ratings in the format "YouTubeID,artist,title,rating"
161# where the columns are listed as "<string>, <string>, <string>, <int>" and
162# the second parameter is the YouTubeID of a song. This function should
163# return the average rating for the song with the inputted YouTubeID. Note
164# that each line of the CSV file is individual rating from a former CSE115
165# student and that each song may be rated multiple times. As you read
166# through the file you'll need to track a sum of all the ratings as well
167# as how many times the song has been rated to compute the average rating.
168
169
170def average_rating(filename, YouTubeID):
171 sum = 0
172 rating = 0
173 with open(filename, newline="") as f:
174 reader = csv.reader(f)
175 for line in reader:
176 if YouTubeID == line[0]:
177 sum = sum + int(line[3])
178 rating = rating + 1
179 return sum / rating
180
181
182# Write a function named 'quantities_owned" that takes one parameter
183# that is a string represent a filename that contains all the trade made by
184# your company throughout the year and returns a dictionary containing the
185# quantity of each stock owned by the company by ticker symbol. Each row of
186# CSV file will contain a single trade in the format "buy_or_sell, quantity,
187# ticker, date" where buy_or_sell is either the string "buy" or "sell",
188# quantity is an integer representing the number of shares traded, ticker is
189# a string representing the ticker symbol being traded, and date is the date
190# of the trade in the format YYYY-MM-DD. This function will return a
191# dictionary with ticker symbols as keys, and the number of shares of each
192# ticker symbol owned as values in integers. In part 3, this dictionary will
193# be used to lookup the number of shares owned for each stock/ticker symbol.
194
195
196def quantities_owned(filename):
197 dict = {}
198 with open(filename, newline="") as f:
199 reader = csv.reader(f)
200 for line in reader:
201 if line[2] in dict:
202 if line[0] == "sell":
203 sell_value = -1 * int(line[1])
204 current_sell_value = sell_value + int(dict[line[2]])
205 dict.update({line[2]: current_sell_value})
206 elif line[0] == "buy":
207 buy_value = int(line[1])
208 current_buy_value = buy_value + int(dict[line[2]])
209 dict.update({line[2]: current_buy_value})
210 else:
211 dict.update({line[2]: int(line[1])})
212 return dict
213
214
215# Write a f(x) named "file_increment" that takes no parameters and
216# doesn't return a value. This f(x) will read the contents of a file
217# named "struggle.txt" which has only 1 line and it contains a
218# well-formed integer. Read this integer and write its value plus 1
219# to a file named "steep.txt". If "steep.txt" already exists it must
220# be overwritten.
221
222
223def file_increment():
224 f_1 = open("chair.txt", 'r')
225 f_2 = open("entry.txt", 'w')
226 for line in f_1:
227 line = line.rstrip('\r\n')
228 f_2.write((str(int(line) + 1)) + '\n')
229
230
231# Write a f(x) that takes a key-value store mapping strings to strings
232# as a parameter and writes the values of the input to a file named
233# "district.txt" with one element per line. If a file named "district.txt"
234# already exists it must be overwritten. The function should not return
235# any value.
236
237
238def write_values(dict):
239 with open("district.txt", 'w') as f:
240 for index in dict.values():
241 f.write(index + '\n')
242
243
244# Define a f(x) that takes a string as a parameter representing the name of a
245# CSV file with 5 columns in the format "<string>,<int>,<int>,<int>,<int>"
246# and writes a file named "cheese.csv" containing all the data from the input
247# file but with a sixth column containing the sum of the values from the fourth
248# and fifth columns.
249
250
251def computed_column(filename):
252 f_1 = open(filename, 'r', newline='')
253 f_2 = open("cheese.csv", 'w', newline='')
254 reader = csv.reader(f_1)
255 writer = csv.writer(f_2)
256 for line in reader:
257 column_six = int(line[3]) + int(line[4])
258 line.append(column_six)
259 writer.writerow(line)
260
261
262# Create a f(x) that takes a string as a parameter representing the name of a
263# CSV file with 5 columns in the format "<string>,<int>,<int>,<int>,<int>"
264# and writes a file named "failure.csv" containing the rows from the input
265# file where the value in the third column is greater than 102.
266
267
268def filter_rows(filename):
269 f_1 = open(filename, 'r', newline='')
270 f_2 = open("failure.csv", 'w', newline='')
271 reader = csv.reader(f_1)
272 writer = csv.writer(f_2)
273 for line in reader:
274 if int(line[2]) > 102:
275 writer.writerow(line)
276
277
278# Define a f(x) that takes a string as a parameter representing the name
279# of a CSV file with 5 columns in the format "<string>,<int>,<int>,<int>,<int>"
280# and writes a file named "overall.csv" containing only the first and
281# fourth columns from the input file.
282
283
284def filter_columns(filename):
285 f_1 = open(filename, 'r', newline='')
286 f_2 = open("overall.csv", 'w', newline='')
287 reader = csv.reader(f_1)
288 writer = csv.writer(f_2)
289 for line in reader:
290 writer.writerow((line[0], line[3]))
291
292
293# Write a f(x) that takes no parameters and does not return a value. There
294# will be a file named "survey.csv" in the testing environment containing
295# survey results as described above (the file has a header line which much
296# be addressed by your code). Write a new file named "histogram.csv" containing
297# 2 columns representing "internet_use,frequency" and no header line that will
298# contain a histogram of the results of responders ages 19 to 39 including
299# the endpoint ages. Your file will have exactly 6 lines with internet_use
300# values of 1-5 corresponding to the intfreq results and 6 for responders who
301# answered 2 to eminuse. Read the survey results file and track how many
302# responders in this age range answered with each of these 6 options and write
303# these counts to your "histogram.csv" file in order of internet_use starting
304# with 1.
305# Example histogram.csv:
306# 1,5
307# 2,7
308# 3,0
309# 4,1
310# 5,2
311# 6,4
312
313
314def internet_histogram():
315 f_1 = open("survey.csv", 'r', newline='')
316 f_2 = open("histogram.csv", 'w', newline='')
317 reader = csv.reader(f_1)
318 writer = csv.writer(f_2)
319 for
320
321
322# Write a f(x) that takes any valid type as a parameter and returns
323# the input as a JSON formatted string. For example, if the input
324# is a key-value store this function should return a JSON string
325# representing an object containing the same data.
326
327
328def to_json(input):
329 return json.dumps(input)
330
331
332# Create a f(x) that takes a JSON formatted string as a
333# parameter and return the data represented by the input
334# in the appropriate types for this language. For example,
335# if the input string represents a JSON object you should
336# return a key-value store containing the same data.
337
338
339def read_json(input):
340 return json.loads(input)
341
342
343# Define a f(x) that takes a JSON formatted string as a
344# parameter in the format "{"attack": <float>, "decay": <float>,
345# "sustain": <float>, "release": <float>}" and returns the
346# value at the key "release".
347
348
349def get_value(str):
350 data = json.loads(str)
351 return data["release"]
352
353
354# Write a f(x) that takes a JSON formatted string as a
355# parameter in the format of an object with keys "x" and
356# "y" each mapping to an array of integers. This is the
357# same format used to plot points on a line graph in Plotly
358# in that each (x[i], y[i]) represents a single point.
359# Return the y-value at x == 2.
360
361
362def get_y(str):
363 dict = json.loads(str)
364 x_arr = dict["x"]
365 y_arr = dict["y"]
366 for value in range(len(x_arr) + 1):
367 if x_arr[value] == 2:
368 return y_arr[value]
369
370
371# Define a f(x) that takes a JSON formatted string as a
372# parameter in the format of an array of objects where each
373# object has keys "mass", "density", "temperature", and
374# "velocity" and each key maps to a floating point number.
375# This function should return the average "density" of all the
376# objects in the array as a JSON string in the format
377# {"density": <Number>}.
378
379
380def json_average(jsonstr):
381 count = 0
382 sum = 0
383 dict = {}
384 data = json.loads(jsonstr)
385 for index in data:
386 y = index["density"]
387 sum = sum + y
388 count = count + 1
389 z = sum / count
390 dict["density"] = z
391 return json.dumps(dict)
392
393
394# Write a f(x) that takes a JSON formatted string as a parameter in
395# the format of an array of objects where each object has keys "mass",
396# "density", "temperature", and "velocity" and each key maps to a floating
397# point number. This function should return the input as a JSON string in
398# the same format but with only the objects with temperature greater
399# than 41.41.
400
401
402def json_filter(jsonstr):
403 list = []
404 dict = json.loads(jsonstr)
405 for index in dict:
406 y = index["temperature"]
407 if y > 41.41:
408 list.append(index)
409 return json.dumps(list)
410
411
412# Write a f(x) that three string parameters representing the protocol,
413# name of a server, and a path for an HTTP GET request in this order.
414# Return the response of an HTTPS GET request to the url formed
415# by these inputs. Recall that a url will follow the format
416# "<protocol>://<server_name>/<path>". The response should be
417# returned as a string.
418
419
420import urllib.request
421
422
423def get_response(protocol, server, path):
424 url = protocol + "://" + server + "/" + path
425 response = urllib.request.urlopen(url)
426 content = response.read().decode()
427 return content
428
429
430# Write a f(x) that takes a string as a parameter representing
431# part of a path of a url and returns the response of an
432# HTTPS GET request to the url "https://fury.cse.buffalo.edu/ps-api/r/<input>"
433# as a string where <input> is the input parameter of this function.
434
435
436def variable_get(input):
437 url = "https://fury.cse.buffalo.edu/ps-api/r/" + input
438 response = urllib.request.urlopen(url)
439 content = response.read().decode()
440 return content
441
442
443# Write a f(x) that doesn't take any parameters and returns the response
444# of an HTTPS GET request to the url
445# "https://fury.cse.buffalo.edu/ps-api/r/melt" as a string.
446
447
448def get_response():
449 url = "https://fury.cse.buffalo.edu/ps-api/r/melt"
450 response = urllib.request.urlopen(url)
451 content = response.read().decode()
452 return content
453
454
455# Write a function named "query_dict" that a key-value store as a
456# parameter mapping strings to floating point numbers. The function
457# will make an HTTPS GET request to the url
458# "https://fury.cse.buffalo.edu/ps-api/a" with a query string containing
459# the same key-value pairs from the input key-value store. The response
460# from the server will be a JSON string representing an object in the
461# format "{"answer": <Number>}" where <Number> is a floating point Number.
462# Return the value at the key "answer" as a float.
463
464
465def query_dict(dictionary):
466 dict_keys = dictionary.keys()
467 url_path = "https://fury.cse.buffalo.edu/ps-api/a"
468 query = "?"
469 for index in dict_keys:
470 value = dictionary[index]
471 query += (index + "=" + str(value) + "&")
472 query = query[:-1]
473 response = urllib.request.urlopen(url_path + query)
474 content = response.read().decode()
475 output = json.loads(content)
476 return float(output["answer"])
477
478
479# Define a f(x) that doesn't take any parameters. The function will
480# make an HTTPS GET request to the url "https://fury.cse.buffalo.edu/ps-api/a"
481# with a query string containing the key-value pairs x=3, y=3, and z=0. The
482# response from the server will be a JSON string representing an object in
483# the format "{"answer": <Number>}" where <Number> is a floating point Number.
484# Return the value at the key "answer" as a float.
485
486def query_string():
487 url_path = "https://fury.cse.buffalo.edu/ps-api/a"
488 query = "?" + "x=3" + "&" + "y=3" + "&" + "z=0"
489 response = urllib.request.urlopen(url_path + query)
490 content = response.read().decode()
491 output = json.loads(content)
492 return float(output["answer"])
493
494
495def flu_season():
496 url = "https://fury.cse.buffalo.edu/ps-api/flutrack/?time=5"
497 response = urllib.request.urlopen(url)
498 content = response.read().decode()
499 output = json.loads(content)
500 return output
501
502
503# set up server
504import bottle
505@bottle.route("/")
506def any_name():
507 response = "<html><body><p>"
508 response = response + "Hello from the server!"
509 response = response + "</p></body></html>"
510 return response
511bottle.run(host="0.0.0.0", port=8080, debug=True)
512
513
514# Module 4
515
516
517# Define a f(x) that takes a list/array of strings as a parameter and
518# sorts the strings in alphabetical order. You must alter the input
519# list/array. This function does not need to return a value.
520
521
522def alphabetical(string):
523 return string
524
525
526def sort_list(list):
527 list.sort(key=alphabetical)
528
529
530# Write a f(x) that takes a list/array of lists/arrays as a parameter where
531# each of the values of input is a list containing 6 integer values. Sort
532# the input based on the values of the first value in each list.
533
534
535def first_value(list):
536 return list[0]
537
538
539def sort_by_index(input):
540 input.sort(key=first_value)
541
542
543# Create a f(x) that takes a list/array of key-value stores as a parameter
544# where each key-value store has keys "power", "purity", "strike", "ability",
545# and "spin" all mapping to integer values. Sort the input based on the values
546# at the key "power".
547
548
549def dict_value(dict):
550 return dict["power"]
551
552
553def sort_kvs(input):
554 input.sort(key=dict_value)
555
556
557# Define a f(x) that takes a list/array of strings as a parameter and
558# sorts the strings by their length.
559
560
561def string_length(string):
562 return len(string)
563
564
565def sort_by_length(input):
566 input.sort(key=string_length)
567
568
569# Create a f(x) that takes a list/array of key-value stores as a parameter
570# where each key-value store has keys "ratings", "budget", and "box_office"
571# where budget and box_office are integers and ratings is a list of integers.
572# Sort the input based on the average of the values in "ratings".
573
574
575def average_rating(dict):
576 sum = 0
577 count = 0
578 for index in dict["ratings"]:
579 sum = sum + index
580 count = count + 1
581 return sum / count
582
583
584def sort_by_average_rating(input):
585 input.sort(key=average_rating)
586
587
588# Write a f(x) that takes a list/array of lists/arrays as a parameter where
589# each of the values of input is a list containing 6 floating point numbers.
590# Sort the input based on multiplication of the third and second values in
591# each list.
592
593
594def third_second_product(list):
595 return list[2] * list[1]
596
597
598def sort_by_product(input):
599 input.sort(key=third_second_product)
600
601
602# Create a f(x) that doesn't take any parameters and doesn't return a value.
603# This function will create a table named "relieve" with any columns you
604# choose in a database with the file name "every.db". If the table already
605# exists your program should not crash (ie. your function will be called twice
606# and should work properly on both calls).Be sure to commit your changes to
607# the database, but do not close the connection to the database since your
608# function will be called more than once. It is ok if you never close the
609# database connections for questions on this site, though in your software
610# you should close the connection.
611
612
613import sqlite3
614
615
616def create_table():
617 conn = sqlite3.connect("every.db")
618 cur = conn.cursor()
619 cur.execute( # Do things here:
620 'CREATE TABLE IF NOT EXISTS relieve (column_one, column_two)'
621 )
622 conn.commit()
623 conn.close() # Don't need .close() for modules but should include elsewhere.
624
625
626# Write a f(x) that takes 3 parameters all of which are strings and doesn't
627# return a value. There is a database saved in a file named "baseball.db"
628# containing a table named "review" with columns "guarantee", "wrong", and
629# "excessive". Insert a new record into this table using the 3 parameters
630# of this function as its values for the three columns. Be sure to commit
631# your changes to the database, but do not close the connection to the database
632# since your function will be called more than once. It is ok if you never
633# close the database connections for questions on this site, though in your
634# software you should close the connection.
635
636
637def add_record(string_1, string_2, string_3):
638 conn = sqlite3.connect("baseball.db")
639 cur = conn.cursor()
640 cur.execute(
641 'CREATE TABLE IF NOT EXISTS review (guarantee, wrong, excessive)'
642 )
643 cur.execute(
644 'INSERT INTO review VALUES (string_1, string_2, string_3)'
645 )
646 conn.commit()
647 conn.close()