Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Q5 : The major flaw with the program provided by Give Music is that it repeatedly reuses similar sections of code without bothering to extract

Q5 : The major flaw with the program provided by Give Music is that it repeatedly reuses similar sections of code without bothering to extract that code into functions.

Your task here is to extract from the program a function tag_position(tag, lines) that returns the index of the given tag in the given list of lines. For example tag_position("", lines) will return 0 for all the test files that you have been provided. If the tag is not in the file, then -1 should be returned (This will be useful for question 8 :-) ).

You should then replace all occurrences of the extracted code with calls to tag_position.

Test that your program still behaves as before, then submit the entire program in the answer box below.

Notes

  • Your program should now have at least two function definitions, tag_position and main. If you have defined other helper functions then they should, of course, be included.
  • The earlier style checks have been tightened slightly and function definitions must contain at most 45 lines/statements per function.

This is the code that need to be changed for each question:

"""main doc""" import os.path def main(): """dd""" filename = None while filename is None: filename = input("Enter a file name: ") if not os.path.isfile(filename): print(filename, "DOES NOT EXIST!") filename = None first = open(filename, encoding="utf-8") lines = first.readlines() first.close() # pull out the header data start = "" # Start tag end = "" # End tag i = 0 found = False while i < len(lines) and not found: lenght = lines[i] if lenght.strip().startswith(start): startline = i # Start line index found = True else: i += 1 i = 0 found = False while i < len(lines) and not found: lemon = lines[i] if lemon.strip().startswith(end): endline = i # End line index found = True else: i += 1 h_lines = lines[startline+1:endline] _, name = h_lines[0].strip().split(':') _, status = h_lines[1].strip().split(':') # pull out the data block start = "" # Start tag end = "" # End tag i = 0 found = False while i < len(lines) and not found: lemon = lines[i] if lemon.strip().startswith(start): startline = i # Start line index found = True else: i += 1 i = 0 found = False while i < len(lines) and not found: lemon = lines[i] if lemon.strip().startswith(end): endline = i # End line index found = True else: i += 1 data_lines = lines[startline+1:endline] data = [] for line in data_lines: _, band_name, amount = line.strip().split(',') amount = float(amount) data.append((band_name, amount)) total = 0 for band_name, amount in data: total += amount # Print the report print("-" * 40) print("Donation Summary") print("-" * 40) print("User name: {}".format(name.title())) print("Account Status: {}".format(status)) if status in ["suspended", "deleted"]: print("*** WARNING ***") print("*** User can't access their account ***") print("-" * 40) for band_name, amount in sorted(data): print("{} ({:.2f})".format(band_name, amount)) print("-" * 40) print("Count: {}".format(len(data))) print("Total: {:.2f}".format(total)) print("-" * 40) main()

For example:

Test Input Result
 
testfile0.txt
Enter a file name: testfile0.txt ---------------------------------------- Donation Summary ---------------------------------------- User name: Lilly Lyvers Account Status: active ---------------------------------------- Black Flag (900.00) Death Cab for Cutie (32.00) Dixie Chicks (72.25) Fugazi (85.75) One Direction (37.00) Poco (6.00) Portishead (87.15) Red Hot Chili Peppers (90.00) Television (86.50) The Drifters (96.00) The Jam (90.00) The Yardbirds (73.00) ZZ Top (24.00) ---------------------------------------- Count: 13 Total: 1679.65 ----------------------------------------
# ignores your call to main # and tests isyour tag_position function file = open("testfile0.txt") lines = file.readlines() file.close() print(tag_position("", lines)) print(tag_position("", lines)) print(tag_position("", lines)) print(tag_position("", lines))
 
0 3 4 18

the second part for the final question:-

Q6: Extract and use a second function tagged_contents(tag_name, lines), which returns the lines between the start and end tags of a block. For instance:

lines = ["not included", "", "included", "also included", "", "not included also" ] 
tagged_contents("data", lines)

will return the list:

["included", "also included"] 

Test your modified program still works, then copy and paste it into the answer box. It must use the function tagged_contents where appropriate.

Note:

  • All functions must now be less than 39 lines long
  • Make sure that you include and use the function tag_position from the last question

For example:

Test Input Result
 
testfile0.txt
Enter a file name: testfile0.txt ---------------------------------------- Donation Summary ---------------------------------------- User name: Lilly Lyvers Account Status: active ---------------------------------------- Black Flag (900.00) Death Cab for Cutie (32.00) Dixie Chicks (72.25) Fugazi (85.75) One Direction (37.00) Poco (6.00) Portishead (87.15) Red Hot Chili Peppers (90.00) Television (86.50) The Drifters (96.00) The Jam (90.00) The Yardbirds (73.00) ZZ Top (24.00) ---------------------------------------- Count: 13 Total: 1679.65 ----------------------------------------
# ignoring main, testing tagged_contents function lines = [ "junk", "junk", "", "Louise", "Katia", "George", "Eiran", "Patrick", "George", "Matthew", "Lucy", "Elizabeth", "", "junk" ] names = tagged_contents("names", lines) print(len(names)) if names != lines[3:-2]: print("Contents are not returned correctly") print(names)
 
9

the final question:

Refactoring the entire program

Your task in this question is to rewrite the entire program so that it is compliant with all our usual style rules, with a limit of 15 lines per function. Your code must behave exactly the same as the original program for any given input. You will need to extract more functions to stay within the new limit of 15 lines per function.

You could write functions with names like:

  • get_file_name
  • get_file_content
  • process_data
  • sum_donations
  • print_report
  • print_report_header
  • print_report_body
  • print_statistics

You are strongly advised to make a series of small changes, testing after each change to make sure you haven't broken the functionality of the program.

Paste your entire working version of the code into the answer box. Note that this program should still use tag_position and tagged_contents that you defined in questions 5 and 6 respectively.

For example:

Input Result
testfile0.txt
Enter a file name: testfile0.txt ---------------------------------------- Donation Summary ---------------------------------------- User name: Lilly Lyvers Account Status: active ---------------------------------------- Black Flag (900.00) Death Cab for Cutie (32.00) Dixie Chicks (72.25) Fugazi (85.75) One Direction (37.00) Poco (6.00) Portishead (87.15) Red Hot Chili Peppers (90.00) Television (86.50) The Drifters (96.00) The Jam (90.00) The Yardbirds (73.00) ZZ Top (24.00) ---------------------------------------- Count: 13 Total: 1679.65 ----------------------------------------

please provide separate codes for each of the first two sub parts and then club it for the last main part. please be available for further queries after the solution has been uploaded. code screenshots with test codes would be appreciated. thanks a lot.

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Students also viewed these Databases questions

Question

Discuss the importance of workforce planning.

Answered: 1 week ago

Question

Differentiate between a mission statement and a vision statement.

Answered: 1 week ago