Question

In: Computer Science

PYTHON Part 2 (separate program) Ask for a file name. Don’t let the program crash if...

PYTHON

Part 2 (separate program)

Ask for a file name. Don’t let the program crash if you enter the name of a file that does not exist. Detecting this will also be discussed on Wednesday. If the file doesn’t exist gracefully display an error message stating the file doesn’t exist and quit the program. It the file does exist read all the values in the file. You will only need to read the file once, or more to the point, only read the file once. After the program has finished reading all the data, display the following information to the screen:

• The minimum value

• The maximum value

• If any values were 100. No output if no values were 100.

• If any values were 0. No output if no values were 0.

• The average – display with 4 places after the decimal point

• The total number of values

• The total number of values greater than or equal to 75

• The total number of values less than 75

• The value closest to 75 (can be 75, less than 75 or greater than 75). abs will be useful for this value.

• The value closest to 75 WITHOUT going over 75 (can be 75, WILL NOT be greater than 75) If no data exists in the file, write out a simple message indicating that there was no data in the file and nothing else.

**I really need something to compare my work to and am struggling with adding the "100 or 0" part.

Solutions

Expert Solution

code in python (code to copy)

from pathlib import Path
# Prints The maximum and minimum value
def printMinMax(list):
    if(len(list)==0):
        print("Min: List is empty!")
        print("Max: List is empty!")
    else:
        min_num=list[0]
        max_num=list[0]
        for item in list:
            min_num=min(min_num, item)
            max_num=max(max_num, item)
        print("Min: ",min_num)
        print("Max: ",max_num)

# f any values were 100. No output if no values were 100.
# If any values were 0. No output if no values were 0
def hundredAndZero(list):
    count100 = 0
    count0 = 0
    for item in list:
        if(item==0):
            count0 = count0 + 1
        if(item==100):
            count100 = count100 + 1
    if(count0!=0):
        print(count0, " value(s) were 0")
    if(count100!=0):
        print(count100, " value(s) were 100")

# The average – display with 4 places after the decimal point
def printAverage(list):
    if(len(list)==0):
        print("Average: List is empty!")
    else:
        sum=0
        for item in list:
            sum = sum + item
        average = float(sum)/len(list) 
        print("Average: %.4f"%average) 
     
# The total number of values greater than or equal to val
def greaterThanEqualTo(list, val):
    count=0
    for item in list:
        if(item>=val):
            count = count+1
    return count

# The total number of values less than val 
def lessThan(list, val):
    count=0
    for item in list:
        if(item<val):
            count = count+1
    return count

# The value closest to val 
# If goOver is true we can cross value and use abs
# if goOver is false then we find strictly less than value 
def closestTo(list, value, goOver):
    closest = -1
    min_diff = 0
    for i in range(len(list)):
        if(not goOver and list[i]>value):
            continue
        if(closest==-1):
            closest=i
            min_diff = abs(list[i]-value)
        else:
            if(min_diff>abs(list[i]-value)):
                closest=i
                min_diff=abs(list[i]-value)
    if(closest==-1):
        print("Closest to %d: List is empty!"%value)
    print("Closest to %d: %d"%(value, list[closest]))

def main():
    filename = input("Enter file name: ")
    f = Path(filename)

    if not f.is_file():
        print("File does not exist!")
    else:
        myfile = open(f, "r")
        nums=[]
        for line in myfile:
            for x in line.split():
                nums.append(int(x))
        printMinMax(nums)
        hundredAndZero(nums)
        printAverage(nums)
        # The total number of values
        print("Total number of values: ", len(nums))
        print("Number of values greater than equal to 75: ",greaterThanEqualTo(nums, 75))
        print("Number of values less than 75: ",lessThan(nums, 75))
        closestTo(nums, 75, True)
        closestTo(nums, 75, False)
        

main()

code screenshot

contents in input.txt

output screenshot 1

output screenshot 2


Related Solutions

Python: Write a program that asks the user for the name of a file. The program...
Python: Write a program that asks the user for the name of a file. The program should display the contents of the file line by line.
Part 1 Ask for a file name. The file should exist in the same folder as...
Part 1 Ask for a file name. The file should exist in the same folder as the program. If using input() to receive the file name do not give it a path, just give it a name like “number1.txt” or something similar (without the quotes when you enter the name). Then ask for test scores (0-100) until the user enters a specific value, in this case, -1. Write each value to the file as it has been entered. Make sure...
PYTHON Modify the program in section Ask the user for a first name and a last...
PYTHON Modify the program in section Ask the user for a first name and a last name of several people.  Use a loop to ask for user input of each person’s first and last names  Each time through the loop, use a dictionary to store the first and last names of that person  Add that dictionary to a list to create a master list of the names  Example dictionary: aDict = { "fname":"Douglas", "name":"Lee" } ...
create a python program that ask for a name and birth year separated by a comma....
create a python program that ask for a name and birth year separated by a comma. the program should keep prompting until the user inputs 'quit'. print the dictionary containing the key value pair name:year in the same order they were inputted. print the name and birth year on a single line for each of the entries. finally print the dictionary with the key value paris swapped and sorted by birth year. from youngest to oldeest.
c++ In this program ask the user what name they prefer for their file, and make...
c++ In this program ask the user what name they prefer for their file, and make a file, the file name should za file. Get a number from the user and save it into the create file. should be more than 20 number in any order. print out all 20 numbers in a sorted array by using for loop, last print out its total and average. At last create a function in which you will call it from main and...
Write a python program: There is a file called file 2. File2 is a txt file...
Write a python program: There is a file called file 2. File2 is a txt file and I have written the contents of file 2 below in the exact format it was in notepad. # This comment does not make sense # It is just to make it harder # The job description starts after this comment, notice that it has 4 lines. # This job description has 700150 hay system points\\ the incumbent will administer the spending of kindergarden...
Python program: Write a program that reads a text file named test_scores.txt to read the name...
Python program: Write a program that reads a text file named test_scores.txt to read the name of the student and his/her scores for 3 tests. The program should display class average for first test (average of scores of test 1) and average (average of 3 tests) for each student. Expected Output: ['John', '25', '26', '27'] ['Michael', '24', '28', '29'] ['Adelle', '23', '24', '20'] [['John', '25', '26', '27'], ['Michael', '24', '28', '29'], ['Adelle', '23', '24', '20']] Class average for test 1...
Write a python program that does the following: Prompt for a file name of text words....
Write a python program that does the following: Prompt for a file name of text words. Words can be on many lines with multiple words per line. Read the file and convert the words to a list. Call a function you created called list_to_once_words(), that takes a list as an argument and returns a list that contains only words that occurred once in the file. Print the results of the function with an appropriate description. Think about everything you must...
Calculating Delivery Cost Program in Python write a program in Python that will ask a user...
Calculating Delivery Cost Program in Python write a program in Python that will ask a user to enter the purchase total, the number of the items that need to be delivered and delivery day. Then the system displays the cost of delivery along with the total cost. Purchase total > $150 Yes Number of the items (N) N<=5 N>=6 Delivery day Same Day Next Day Same Day Next Day Delivery charges ($) 8 N * 1.50 N * 2.50 N...
C++ Code while loops. 1. Ask for file name and open file. 2. Do a priming...
C++ Code while loops. 1. Ask for file name and open file. 2. Do a priming read and make a while loop that A) Reads in numbers B) Sums them up. C) Counts how many there are. D) Prints "With 10 numbers, the average is blank.." every 10 numbers. So with every 10 numbers read in print the average. 3. After the loop calculate average of all numbers and print it. So for example once the file is open the...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT