use python please Part V: Fetch Information (20 points) In this part we will gen
ID: 3736418 • Letter: U
Question
use python please
Part V: Fetch Information (20 points) In this part we will generalize the results of the previous part to files that contain information other than course enrollment data. The first line of the file ill contain a comma-separated list of strings that define the format of the file. Some examples: e Car data: Make, Model, Year CPU data: Manufacturer, Model, NumCores, ClockSpeed House data: Town, Year , Price, NumRooms, Taxes Write a function fetch.value ) that takes the following arguments, in this order: 1. filename: The name of a file the function will read data from. All fields in the file will be separated by commas. You may assume that the file is always validly formatted 2. selected.field: The name of the field from which we are reading values 3. searched.field: The name of the field we are using to search the data. 4. searched.value: The value of the searched.field that we are trying to match. To understand the meaning of these arguments, suppose the function were called on CPU data (with fields Manufacturer, Mode1, NumCores, ClockSpeed) with the following arguments: CSE 101 Spring 201:8 Homework #4 Page 8 fetch.value('cpu.txt', Manufacturer, 'ClockSpeed', '3'). This function call indicates that we want a list of CPU manufacturers whose CPU's ClockSpeed field has a value of 3'. (Duplicated val- ues are expected, and the number of copies of a selected value must equal the number of lines that match the search.value. Do not sort the returned list.) Note that ALL values in the file are treated as strings, even values we would normally treat as numerical More generally speaking, the function reads from the given file and finds lines where the value in the searched.field "column" matches the searched.value function argument. When such a line is found, the function appends the corresponding value of selected.field column into the returned listExplanation / Answer
def fetch_value(file,selected,searched,value): L=[] Colnames=[] ind1=-1 ind2=-1 first=True with open(file,'r') as f: for lines in f.readlines(): if first: Colnames=lines.split(',') for i in range(0,len(Colnames)): name=Colnames[i].strip() if name==selected: ind1=i if name==searched: ind2=i first=False data=lines.split(',') if data[ind2].strip()==value: L.append(data[ind1]) return L
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.