Python Forum
Help on Creating Program to find the Median and Mode by hand
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help on Creating Program to find the Median and Mode by hand
#1
My assignment is to create a program that reads a text file with numbers and outputs all the statistics found here. Similar to the output below. There are four different files that the program needs to evaluate in which there is an even number such that the median is between two numbers, an odd amount of numbers such that the median is the center number, a file with only one number, and an empty file. My program used to work for all cases in finding all the statistics except for the mode, but since I have tried to add new code to find the mode my program keeps repeating the line, "Enter the name of the text file", but I'm not sure why. I have tried to find the mode in a couple of ways from code that I have found online and from suggestions that my teacher gave me to use. I have also written the code directly below to try to find the mean, but I think that I'm missing a couple of lines to compare the frequency of the different values. I really appreciate your help.
number_counts = {}
                for number in num_list:
                    if number in number_counts:
                        number_counts[number] += 1
                    else:
                        number_counts[number] = 1

                for number in number_counts:
                        Count = number_counts[number]
                        mode = max(Count)
                for number in num_list
                Count = number_counts[number]
Sum: 56110
Count: 100
Average: 561.1
Maximum: 995
Minimum: 8
Range: 987
Median: 564.5
Mode: [660, 476]
The current code that I have written is

print('This program reads a series of integer numbers from a file and determines and displays statistics about the integers.')

num_list = []

again = 'y'

while again =='y':
        try:
#The name of the file should include a .txt ending
            name_of_file = input( 'Enter the name of the text file. ')

            object_file = open(name_of_file, 'r')
            count=0
            total=0

            for line in object_file:
                line=line.rstrip('\n')
                line=int(line)
                total +=(line)
                count += 1
                num_list.append(line)

            num_list.sort()
            length = len(num_list)
            if length ==0:
                    print('There are no numbers in',name_of_file)
                    print('Would you like to do evaluate another file?')
                    again=input('y = yes, anything else = no: ')
                    print()
                    break
            elif length == 1:
                median = num_list[0]
                
            elif (length % 2 == 0):
                median = (num_list[(length)//2] + num_list[(length)//2-1]) / 2
            else:
                median = num_list[(length-1)//2]
            # start of trying to find the mode

                numbers = dict()

                for item in num_list:
                    if item not in numbers:
                        numbers[item] = 1
                    else:
                        numbers[item] = numbers[item] + 1

                max_count = 0

                for key in numbers:
                    if numbers[key] > max_count:
                        max_count = numbers[key]

                max_modal_elements = []

                for key in numbers:
                    if numbers[key] == max_count:
                        max_modal_elements.append(key)
        
                mode = min(max_modal_elements)


                max_val = max(num_list)
                min_val = min(num_list)

                average = total/count
                Range = max_val-min_val

                           
           

                print('File name: ',name_of_file)
                print('Sum: ',total)
                print('Count: ',count)
                print('Average: ',average)
                print('Maximum: ',max_val)
                print('Minimum: ',min_val)
                print('Range: ',Range)
                print('Median: ',median)
                print('Mode: ',mode)
                

                print('Would you like to do evaluate another file?')
                again=input('y = yes, anything else = no: ')
                print()
                                            

        except IOError:
            print('An error occurred trying to read')
            print('the file', name_of_file)

        except ValueError:
            print('Non-numeric data found in the file.')        
Reply
#2
Quote:my program keeps repeating the line, "Enter the name of the text file"
while again =='y':
The variable named again does not change for either of the following 2 conditions
            elif length == 1:
                median = num_list[0]
                 
            elif (length % 2 == 0): 
You want to ask once, at the end of the code under the try statement.

The mode is the number that occurs the most. Note that this will only find one mode, so if there is more than one, it will find the last one in the dictionary
## I have no time to test this so you will have to fix any errors
                number_counts = {}
                for number in num_list:
                    if number in number_counts:
                        number_counts[number] += 1
                    else:
                        number_counts[number] = 1
 
                ## you now have a dictionary, number_counts, that contains
                ## the number of times each number occurs
                ## so you have to loop through the dictionary and
                ## and find the one(s) that have the highest count,
                ## and keep track of that dictionary key, which
                ## allows you to get the current mode from the dictionary
                ## and compare to the next value in the for
                mode_key=number_counts.keys()[0]  ## initialize from first dictionary key
                print("initial value is", mode_key)  ## while testing
                for number in number_counts:
                    count = number_counts[number]
                    if count > number_counts[mode_key]:  ## greater than current mode
                        mode_key=number  ## update with new dictionary key  
Reply
#3
When you say "You want to ask once, at the end of the code under the try statement." I'm a little bit confused as to what line this should be placed at specifically. I fixed the case when the length is equal to zero, so that the statement is only displayed once, but was unsure in the code window I have below where this should be placed. Thanks again for your help. I really appreciate it.

print('This program reads a series of integer numbers from a file and determines and displays statistics about the integers.')

num_list = []

again = 'y'

while again =='y':
        try:
#The name of the file should include a .txt ending
            name_of_file = input( 'Enter the name of the text file. ')

            object_file = open(name_of_file, 'r')
            count=0
            total=0

            for line in object_file:
                line=line.rstrip('\n')
                line=int(line)
                total +=(line)
                count += 1
                num_list.append(line)

            num_list.sort()
            length = len(num_list)

            if length ==0:
                    print('There are no numbers in', name_of_file)
                    again!='y'
                    
            elif length == 1:
                median = num_list[0]
                
            elif (length % 2 == 0):
                median = (num_list[(length)//2] + num_list[(length)//2-1]) / 2
            else:
                median = num_list[(length-1)//2]
            

                number_counts = {}
                for number in num_list:
                    if number in number_counts:
                        number_counts[number] += 1
                    else:
                        number_counts[number] = 1

                mode_key=number_counts.keys()[0]  ## initialize from first dictionary key
                print("initial value is", mode_key)  ## while testing
                for number in number_counts:
                    Count = number_counts[number]
                    if Count > number_counts[mode_key]:  ## greater than current mode
                        mode_key=number  ## update with new dictionary key


                max_val = max(num_list)
                min_val = min(num_list)

                average = total/count
                Range = max_val-min_val

                           
           

                print('File name: ',name_of_file)
                print('Sum: ',total)
                print('Count: ',count)
                print('Average: ',average)
                print('Maximum: ',max_val)
                print('Minimum: ',min_val)
                print('Range: ',Range)
                print('Median: ',median)
                print('Mode: ',mode_key)
                

                print('Would you like to do evaluate another file?')
                again=input('y = yes, anything else = no: ')
                print()
                                            

        except IOError:
            print('An error occurred trying to read')
            print('the file', name_of_file)

        except ValueError:
            print('Non-numeric data found in the file.')        
Reply
#4
You want to move it left one level so it is under the try (2 levels if you want to also ask when there is an exception).
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Python Program to Find the Factorial of a Number elisahill 2 1,423 Nov-21-2022, 02:25 PM
Last Post: DeaD_EyE
  Calculate median for school grades per subject siki 1 1,908 May-10-2021, 11:41 AM
Last Post: jefsummers
  Any pointers on my programm before I hand it in?(I'm new to python, so go easy on me) blacklight 3 1,959 Jul-07-2020, 01:19 PM
Last Post: deanhystad
  Median of the age row - tsv file sonxy 3 2,981 Apr-09-2018, 11:48 PM
Last Post: micseydel
  Program: count and find Truman 3 4,641 Feb-11-2018, 11:06 PM
Last Post: Larz60+
  Creating Program Homework ShakenBake 2 2,977 Feb-10-2018, 11:42 AM
Last Post: wavic
  Masked median filters Jim421616 0 2,838 Aug-24-2017, 01:30 AM
Last Post: Jim421616

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020