Question

In: Computer Science

Please use python3 Create the function team_average which has the following header def team_average(filename): This function...

Please use python3

Create the function team_average which has the following header

def team_average(filename):

This function will return the average number of games won by the Red Sox from a text file with entries like this

2011-07-02      Red Sox @  Astros       Win 7-5
2011-07-03      Red Sox @  Astros       Win 2-1
2011-07-04      Red Sox vs Blue Jays    Loss 7-9

This function should create a file object for the file whose name is given by the parameter filename.

If the file cannot be opened, use a try/except statement to print an error message and don't do any further work on the file.

The function will count the number of lines and the number of games the Red Sox won and use these values to compute the average games won by the team.

This average should be expressed as an integer.

Test Code

Your hw2.py file must contain the following test code at the bottom of the file

team_average('xxxxxxx')
print(team_average('red_sox.txt'))

For this test code to work, you must copy into your hw2 directory the file red_sox.txt from /home/ghoffman/course_files/it117_files.

To do this go to your hw2 directory and run cp /home/ghoffman/course_files/it117_files/red_sox.txt .

Suggestions

Write this program in a step-by-step fashion using the technique of incremental development.

In other words, write a bit of code, test it, make whatever changes you need to get it working, and go on to the next step.

  1. Create the script hw2.py using nano or some other Unix text editor.
    Enter the header for team_average into the script.
    Under this header write the Python statement pass.
    Copy the test code above into the script.
    Make the script executable.
    Run the script.
    If all you see is None, proceed to the text step.
  2. Remove the pass statement.
    In its place write the function code to open the file for reading.
    This code should print an error message and exit the function if the file cannot be opened for reading.
    Run the script.
    You should see
    Cannot open xxxxxxx
    None
  3. Modify the function so it prints out the lines of the file.
  4. Modify the function to use the split string method to create a list from the from the different fields in a line. Print this list.
  5. For each line, get the value of the won_lost field and print it.
    This field is second to last entry in the list you created by using the split method.
    The lists will have different lengths, since some team have a single word as their name, and others have two words, e.g. White Sox.
    The easiest way to get the second to last field is to use a negative index.
    Print the value of won_lost field.
  6. Comment out or delete the line that prints the won_lost field.
    Initialize an accumulator to count the number of lines.
    Increment this accumulator inside the for loop.
    Return the total number of lines.
  7. Initialize an accumulator to count the number of Red Sox wins.
    In the for loop increment this accumulator every time the value of won_lost is "Win".
    Return the number of games won.
  8. Change the return statement so it returns integer percent of the number of games the Sox won.

Output

When you run the completed script, you should see

Error: Unable to open xxxxxxx
76

Solutions

Expert Solution

def team_average(fileName):
    try:
        matchesWon = 0
        totalMatches = 0
        with open(fileName, 'r') as file:  # file opened
            for line in file:  # ging through each line
                totalMatches += 1  # number of lines is number of matches
                tokens = line.split()  # splitting each line by spaces
                if tokens[-2].lower() == 'win':  # at -2 index, result of match is stored
                    #index -2 is counted fro, right,so last position is -1, second last position is -2
                    matchesWon += 1  # if result is win, increment counter
        return int(matchesWon * 100 / totalMatches)  # integer percent returned
    except IOError:
        print('Error : Unable to open', fileName)


team_average('xxxx')
print(team_average('red_sox.txt'))


Related Solutions

In python def lambda_2(filename): # Complete this function to read grades from `filename` and map the...
In python def lambda_2(filename): # Complete this function to read grades from `filename` and map the test average to letter # grades using map and lambda. File has student_name, test1_score, test2_score, # test3_score, test4_score, test5_score. This function must use a lambda # function and map() function. # The input to the map function should be # a list of lines. Ex. ['student1,73,74,75,76,75', ...]. Output is a list of strings in the format # studentname: Letter Grade -- 'student1: C' #...
Please answer all qestions 1) Within a function header, for example: def gcd(a, b): The variables...
Please answer all qestions 1) Within a function header, for example: def gcd(a, b): The variables that appear within parentheses are called what? Group of answer choices a)variables b)attributes c)parameters d)arguments 2)Question 31 pts Within a function call, for example: g = gcd(142, b); The text that appears within parentheses is called what? Group of answer choices a) variables b) attributes c) parameters d)arguments 3) Question 42 pts Given this function header: def compute(x, y, z): And this code to...
C++ Only Create a function named PrintStudents, which takes a string input filename and an integer...
C++ Only Create a function named PrintStudents, which takes a string input filename and an integer minimum score value and a string output file name as a parameters. The function will read the student scores and names from the file and output the names of the students with scores greater than or equal to the value given. This function returns the integer number of entries read from the file. If the input file cannot be opened, return -1 and do...
Please solve the following question by Python3. Code the function calc_tot_playtime to calculate the total playtime...
Please solve the following question by Python3. Code the function calc_tot_playtime to calculate the total playtime by user and game. Each element in input is of the format "user_id, game_id, total_playtime_in_minute". Input is a list of strings of the above format. Output should be sorted by user_id, game_id in ascending order. Example: Input: ["1,10,20", "1,15,10m", "1,10,10m", "2,10,40m", "2, 20, 10m"] output: [('1', '10', 30), ('1', '15', 10), ('2', '10', 40), ('2', '20', 10)] Functions are defined below: def calc_total_playtime(input_data=None): """...
PYTHON. Create a function that accepts a filename where in each line there is a name...
PYTHON. Create a function that accepts a filename where in each line there is a name of a type of bird. use a python dictionary in order to count the # of time each bird appears. (1 line = 1 appearance) Loop over your dict. to print each species and the # of times it was seen in the file once all lines have been counted. return dictionary containing count the filename opens this: blackbird canary hummingbird canary hummingbird canary...
Use python. redact_file: This function takes a string filename. It writes a new file that has...
Use python. redact_file: This function takes a string filename. It writes a new file that has the same contents as the argument, except that all of the phone numbers are redacted. Assume that the filename has only one period in it. The new filename is the same as the original with '_redacted' added before the period. For instance, if the input filename were 'myfile.txt', the output filename would be 'myfile_redacted.txt'. Make sure you close your output file.
Create a header file, iofunctions.h, containing the following function prototypes. (don't forget to follow the coding...
Create a header file, iofunctions.h, containing the following function prototypes. (don't forget to follow the coding style) int readfile( struct pokemon pokearray[ ], int* num, char filename[ ] ); int writefile( struct pokemon pokearray[ ], int num, char filename[ ] ); Then, create a source file, iofunctions.c, defining the functions above. Specifications The readfile function will read the data from a text file and store it in the array called by pokearray. It must not load the pokemons more than...
Please answer using python 3 and def functions! Lab 2 Drill 3: (function practice) create and...
Please answer using python 3 and def functions! Lab 2 Drill 3: (function practice) create and use a function named highest() that takes three inputs and returns the highest number. After you have got it working, try calling the function with inputs ‘hat’, ‘cat’, ‘rat’.
Create a new Python program (you choose the filename) that contains a main function and another...
Create a new Python program (you choose the filename) that contains a main function and another function named change_list. Refer to the SAMPLE OUTPUT after reading the following requirements. In the main function: create an empty list. use a for loop to add 12 random integers, all ranging from 50 to 100, to the list. use second for loop to iterate over the list and display all elements on one line separated by a single space. display the 4th element,...
PLEASE USE MEHODES (Print part of the string) Write a method with the following header that...
PLEASE USE MEHODES (Print part of the string) Write a method with the following header that returns a partial string: public static String getPartOfString(int n, String firstOrLast, String inWord) Write a test program that uses this method to display the first or last number of characters of a string provided by the user. The program should output an error if the number requested is larger than the string. SAMPLE RUN #1: java PartOfString Enter a string: abracadabra↵ Enter the number...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT