Write a program that first reads in the name of an input file and then reads the input file using the file.readlines() method. The input file contains an unsorted list of number of seasons followed by the corresponding TV show. Your program should put the contents of the input file into a dictionary where the number of seasons are the keys, and a list of TV shows are the values (since multiple shows could have the same number of seasons).
Sort the dictionary by key (least to greatest) and output the results to a file named output_keys.txt, separating multiple TV shows associated with the same key with a semicolon (;). Next, sort the dictionary by values (alphabetical order), and output the results to a file named output_titles.txt.
This is my current code but it doesn't produce any output. I need help with it.
# Type your code here
def file_reader(file_name):
tv_dict = {}
try:
with open(file_name,"r") as myfile:
details = myfile.readlines()
for item in details:
k,v =item.strip().split(maxsplit=1)
if int(k) in tv_dict:
tv_dict[int(k)].append(v)
else:
tv_dict[int(k)]=[v]
except:
return None
return tv_dict
def sorting(dict_t):
sort1 = {}
sort2 = {}
for k in sorted(dict_t.keys()):
sort1[k]=list(set(dict_t[k]))
sort2[k]=sorted(list(set(dict_t[k])))
out1 = ""
out2 = ""
for k,v in sort1.items():
out1+=str(k)+": "+"; ".join(v)+"\n"
for key,value in sort2.items():
out2+=str(k)+": "+"; ".join(v)+"\n"
return out1[:-1],out2[:-1]
def output_file(output,filename):
with open(filename,"w") as outfile:
outfile.write(output)
def main():
input_file = input("Enter input file name:")
tv_dict = file_reader(input_file)
if tv_dict is None:
print("Error: File Not Found: {}".format(input_file))
return
output_file1 ="output_keys.txt"
output_file2 ="output_titles.txt"
out1,out2 = sorting(tv_dict)
output_file(out1, output_file1)
output_file(out2, output_file2)
main()
def readInputFile(filename):
shows_dict = {} #create an empty dictionary
infile = open(filename, 'r') #open input file
lines = infile.readlines() #read all lines of the file
for i in range(0, len(lines), 2): #loop for all lines, with increment of 2
numOfSeasons = int(lines[i].strip()) #get number of seasons from ith line
show = lines[i+1].strip() #get show name from (i+1)th line
if numOfSeasons not in shows_dict.keys(): #create a key for numOfSeasons if it not exists
shows_dict[numOfSeasons] = []
shows_dict[numOfSeasons].append(show) #add the show to the list of values for that key
#print(shows_dict)
return shows_dict #return the dictionary
def outputSortedbyKeys(dict, filename):
print("Sorting by keys: ")
outfile = open(filename,'w') #open output file for writing
for key in sorted(dict.keys()): #sort the keys
outfile.write('{}: {}\n'.format(key,'; '.join(dict.get(key)))) #write the key: values separated by ;
print('{}: {}'.format(key,'; '.join(dict.get(key))))
print(filename + " written successfully\n")
def outputSortedbyValues(dict, filename):
titles = []
for key in dict.keys(): #get all the values and store in titles list
for val in dict[key]:
titles.append(val)
outfile = open(filename,'w') #open output file for writing
for title in sorted(titles): #sort the titles list and write to file
outfile.write('{}\n'.format(title))
print(title)
print(filename + " written successfully\n")
def main():
filename = input("Enter the input filename: ") #read name of inputfile
shows_dict = readInputFile(filename) #read data from file and get the dictionary
outputSortedbyKeys(shows_dict , 'output_keys.txt') #sort and output dictionary sorted by keys
outputSortedbyValues(shows_dict , 'output_titles.txt') #sort and output dictionary sorted by values
main()
Python 12.10 LAB: Sorting TV Shows (dictionaries and lists)
Write a program that first reads in the name of an input file
and then reads the input file using the file.readlines() method.
The input file contains an unsorted list of number of seasons
followed by the corresponding TV show. Your program should put the
contents of the input file into a dictionary where the number of
seasons are the keys, and a list of TV shows are the values (since...
Python problem.
3. (6 pts) Define the following four sorting functions: each takes an argument that is a list of int or str or both values (otherwise raise an AssertionError exception with an appropriate error message) that will be sorted in a different way. Your function bodies must contain exactly one assert statement followed by one return statement. In parts a-c, create no other extra/temporary lists other than the ones returned by calling sorted. a. (2 pts) Define the mixed...
I have a multithreaded java sorting program that works as follows: 1. A list of double values is divided into two smaller lists of equal size 2. Two separate threads (which we will term sorting threads) sort each sublist using a sorting algorithm of your choice 3. The two sublists are then merged by a third thread merging thread that merges the two sublists into a single sorted list. SIMPLE EXECUTION >java SortParallel 1000 Sorting is done in 8.172561ms when...
please complete the missing function only to figure out how
many numbers fall within the range of 90 through 99 total of 29
values
in
C
6 finclude "lab5.h" 8 const char *FILENAME() - / array of the data file names * ("lab5a.dat", "lab5b.dat", NULL); 12 int main(void) 13 int file count = 0; keeps track of which file we are on/ int check overflow - 0; / counter to prevent array overflow int real filesize = 0; /actual count...
I'm trying to sort a list of students from a text file in python(3.7) with three separate sorting functions (Bubble, selection, insert) I'm not sure to why as its not working I'm going to guess its because I'm not using the swap function I built. Every time I run it though I get an error that says the following Traceback (most recent call last): File "C:/Users/tkoto/Desktop/SearchAndSortLab.py", line 146, in <module> main() File "C:/Users/tkoto/Desktop/SearchAndSortLab.py", line 122, in main studentArray.gpaSort() File "C:/Users/tkoto/Desktop/SearchAndSortLab.py",...
can
someone please help me write a python code for this urgently, asap
Question: Write a Python function, minmp, that is passed a file name and a metal alloy's formula unit structure*". The file will contain metal elements and their properties. The function will return a tuple of the element from the formula with the lowest melting point and that melting point Write a second function, molform, that will be called by the first function, to take the metal alloy's...
QUESTION The ReadFile class opens and reads a text file. The WriteFile class opens and writes to a file. Compile and run these programs. There are several ways to read/write text files. The examples shown here are just one way of achieving this. Look at the API for the BufferedReader class. The readline() method is a simple way to read the text file line by line. It returns null when the end of the file has been reached. https://docs.oracle.com/javase/8/docs/api/java/io/BufferedReader.html Look...
PYTHON The provided code in the ATM program is incomplete. Complete the run method of the ATM class. The program should display a message that the police will be called after a user has had three successive failures. The program should also shut down the bank when this happens. [comment]: <> (The ATM program allows a user an indefinite number of attempts to log in. Fix the program so that it displays a message that the police will be called...
My tests for sorting algorithms are not working. sorting.py has 6 sorting algorithms and test_sorting.py has test cases to run those algorithms, but test cases are not working. please correct the errors in test_sorting.py file so that it can test all the sorting algorithms. WARNING: DON'T COPY AND PASTE THE QUESTION IN ANSWER. I WILL REPORT YOU. sorting.py # 1. selection sort # 2. insertion sort # 3. shell sort # 4. heap sort # 5. merge sort # 6....
Hey I have a task which consists of two part. Part A asks for
writing a program of WORD & LINE CONCORDANCE
APPLICATION in python which I have completed it.
Now the second part has given 5 dictionary implementation codes
namely as: (ChainingDict, OpenAddrHashDict with linear probing,
OpenAddrHashDict with quadratic probing, and 2 tree-based
dictionaries from lab 12 (BST-based dictionary implementation) and
asks for my above program WORD & LINE CONCORDANCE
APPLICATION to use these implemented code and
show the time...