Python Forum

Full Version: Help on Creating Program to find the Median and Mode by hand
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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.')        
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  
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.')        
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).