QuestionQuestion

Transcribed TextTranscribed Text

This lab provides an additional exercise on iteration over lists. Additionally it provides an exercise on file I/O. command line arguments, and exceptions (what to do when things go wrong)! unzip Lab7.zip Grouping For this part of the lab you will develop function in groups py define the following function groups The groups of function takes list of values as its only argument This function wil group the second three form group, etc This function mus return list of lists where each sub -list (excluding the elements the input list into groups of three (i.e.. the first three consecutive values form group; perhaps, the last) is: group of three values. If there are not enough values to fill the last grouping, then it will contain fewer than three values. As examples, consider the following >>> groups of 3([1,2,3,4,5,6,7,8,9] [[1,2,3] [4,5,6],17,8,9]] >>> groups of_3([1,2,3,4,5,6,7,8]) [[1,2,3],[4,5,6],17,1 8]] Write three tests for your function in groups tests.py File Input, Command Line Arguments, try/except Create parse file py in directory file Command line stuff Write program that takes at least one. and optionally second, command line argument. The required argument should be the name of file to open for parsing The optional second argument should be flag If the user provides the wrong number of arguments or the optional argument is not -s'. then print the message Usage: [-s] file name and terminate the program using exit File /O and Exceptions Next your program should attempt to open the given inpui file for reading Opening the file could fail for several reasons (e.g the given file doesn't exist, the given file doesn't have the needed permissions, etc. ) Failure to open the file could result in an exception being raised. This will cause your program crash! Exceptions are covered in the next course, so we will use simple case here. In short, your code will try something that something works, then great continue on If that something does not work then "catch' the exception and so something else Youcan think of this asking for forgiveness instead of asking for permission The code outline below gives the simple structure of working with operations that may raise exceptions. try: what you want to attempt to do except: # what to do if the previous code raises an exception Should opening the file raise an exception print the message 'Unable to open [filename] and quit your program using exit Replace [filename] with the name of the actual file. (Alternatively, if you know how. you may print the message in the Exception that was raised.) Your program should open the file and read each line. The file will consist of integers, floats, and "other" strings that are not ints or floats You should keep count of each kind of thing read from the file and print the results when you are finished reading the entire file For example, given the following input file abc123 34 2.34 h 3333333 Your program should output: Ints: Floats: 1 Other: So what about that option? Should the user request that option, additionally keep track of the sum of all the integers and floats in the file and print the sum after printing the counts of each of the word "types' Sample Runs Sample run using the file testO.Ixt that comes with this lab (Note: The'> sample prompt.) python3 parse_file testO.txt Ints: Floats Other: Sample run using the file testO.ixt that comes with this lab and the soption python3 parse file.py testO.ixt Ints: Floats: 3 Other: Sum: 127 17 Note that the option should work on eitherside of the inpul file python3 parse file. py testO.txt - Ints: Floats: Other: Sum: 127.17 Failure for incorrect number of arguments python3 parse file.py Usage: file name Failure for incorrect option. python3 parse file py testO.txt Usage: file name Failure because the program couldn't open the file. python3 parse file.py junk.ixt Unable to open junk.txt Some Hints How do you figure out fa 'word' in the file an integer, float. or something else? Some helpful hints Don't forget you can split each line into words A word that consists of all digits an integer Test for that first Remember the string function isdigit For example: s = ["this', 'is','a', test'. 12'] s[4] isdigit() will returns True Attempting to use the float function on something that is float will succeed. Attempting to use it on something that isn't float will fail (i.e. raise an Exception) Demo and submit your files in the PlyLearn.

Solution PreviewSolution Preview

These solutions may offer step-by-step problem-solving explanations or good writing examples that include modern styles of formatting and construction of bibliographies out of text citations and references. Students may use these solutions for personal skill-building and practice. Unethical use is strictly forbidden.

import sys

filename = None
flag = False

'''
Process command line inputs
'''
if len(sys.argv) == 2:
    filename = sys.argv[1]
elif len(sys.argv) == 3 and sys.argv[1] == '-s':
    flag = True
    filename = sys.argv[2]
elif len(sys.argv) == 3 and sys.argv[2] == '-s':
    flag = True
    filename = sys.argv[1]
else:
    print('Usage: [-s] file_name')

'''
Attempt to read file
'''
if filename != None:
    try:
       ints = []
       floats = []
       other = []
       '''
       Read file line by line
       '''
       with open(filename) as f:
            for line in f:
                params = line.strip().split()
                for param in params:
                   '''
                   Determine if value is int, float, or other
                   '''
                   if param.isdigit():
                        ints.append(int(param))
                   else:
                        try:
                            param = float(param)
                            floats.append(param)
                        except:
                            other.append(param)
       '''
       Print summary...

By purchasing this solution you'll be able to access the following files:
Solution.zip.

$60.00
for this solution

PayPal, G Pay, ApplePay, Amazon Pay, and all major credit cards accepted.

Find A Tutor

View available Python Programming Tutors

Get College Homework Help.

Are you sure you don't want to upload any files?

Fast tutor response requires as much info as possible.

Decision:
Upload a file
Continue without uploading

SUBMIT YOUR HOMEWORK
We couldn't find that subject.
Please select the best match from the list below.

We'll send you an email right away. If it's not in your inbox, check your spam folder.

  • 1
  • 2
  • 3
Live Chats