In: Computer Science
Exercise 9 – Writing values from a list into a file Complete the function design for the write_most_frequent() function, which takes 4 parameters, a string, a list of tuples, an integer, and another string: • The first string represents the name of the file to write to (with the append usage mode) • The list of tuples contains the information to write. Assume the list has already been sorted. • The integer represents the number of elements to read from the list and write to the file • The title should be written to the file before writing data from the list.
def test_write_most_frequent():
print("testing write_most_frequent")
list1 = [("a",27), ("bc",25), ("defg",21), ("hi",21),
("jk",18),
("l",17),
("m",16), ("nop", 15), ("qr", 14), ("s", 13),
("t",10),
("uv",9), ("x",5), ("yz",2)]
write_most_frequent("test_output.txt", list1, 5,
"Alphabet Statistics")
# Should append to a file called test_output.txt the
following:
# Results for Alphabet Statistics:
# a: 27
# bc: 25
# defg: 21
# hi: 21
# jk: 18
write_most_frequent("test_output.txt", list1, 12,
"Large Alphabet Statistics")
# Should append to a file called test_output.txt the
following:
# Results for Large Alphabet Statistics:
# a: 27
# bc: 25
# defg: 21
# hi: 21
# jk: 18
# l: 17
# m: 16
# nop: 15
# qr: 14
# s: 13
# t: 10
# uv: 9
-------------------------------------
# (str, (list of tuple), int, str -> None)
# appends to the file named filename data from the first
# n elements found in the given list; assumes the list is
sorted;
# the title given should be written on its own line first
def write_most_frequent(filename, list, n, title):
print("Fix me")
If you have any queries write a comment. If you have understood upvote thank you.
SOLUTION:
def write_most_frequent(filename, list1, n, title):
file=open(filename,"a+")
##open file in append and write mode so that the data is appended
to the file
file.write("Result for "+title+"\n")
##append title to the file start
for i in range(n):##append the data to the file
file.write(list1[i][0]+" : "+str(list1[i][1])+"\n")
file.close()
##close the file
def test_write_most_frequent():
print("testing write_most_frequent")
##list of data
list1 = [("a",27), ("bc",25), ("defg",21), ("hi",21),
("jk",18),
("l",17), ("m",16), ("nop", 15), ("qr", 14), ("s", 13),
("t",10), ("uv",9), ("x",5), ("yz",2)]
##call function
write_most_frequent("test_output.txt", list1, 5, "Alphabet
Statistics")
##call the test write most frequent
test_write_most_frequent()
CODE IMAGE:
OUTPUT TEXT FILE: