pythontext-filesreturn-valuefilereader

Finding largest value in a file and printing out value w name


I need to create a progtam that opens a file then reads the values inside the file and then prints out the name with the largest value.

The file contains the following info:

Juan,27
Joe,16 
Mike,29
Roy,10

Now the code I have is as follows:

UserFile = input('enter file name')
FileOpen = open(User File,'r')
for lines in User File:
    data = line.split(",")
    name = data[0]
    hrs = data[1]
    hrs = int(hrs)
    LHRS = 0
    if hrs > LHRS:
    LHRS = hrs
    if LHRS == LHRS:
        print('Person with largest hours is',name)

The following prints out:

Person with the largest hours is Juan
Person with the largest hours is Mike

How can I make it so it only prints out the true largest?


Solution

  • While your effort for a first timer is pretty impressive, what you're unable to do here is.. Keep track of the name WHILE keeping track of the max value! I'm sure it can be done in your way, but might I suggest an alternative?

    import operator
    

    Let's read in the file like how I've done. This is good practice, this method handles file closing which can be the cause of many problems if not done properly.

    with open('/Users/abhishekbabuji/Desktop/example.txt', 'r') as fh:
        lines = fh.readlines()
    

    Now that I have each line in a list called lines, it also has this annoying \n in it. Let's replace that with empty space ''

    lines = [line.replace("\n", "") for line in lines]
    

    Now we have a list like this. ['Name1, Value1', 'Name2, Value2'..] What I intend to do now, is for each string item in my list, take the first part in as a key, and the integer portion of the second part as the value to my dictionary called example_dict. So in 'Name1, Value1', Name1 is the item in index 0 and Name2 is my item in index 1 when I turn this into a list like I've done below and added the key, value pair into the dictionary.

    example_dict = {}
    for text in lines:
        example_dict[text.split(",")[0]] = int(text.split(",")[1])
    print(example_dict)
    

    Gives:

    {'Juan': 27, 'Joe': 16, 'Mike': 29, 'Roy': 10}
    

    Now, obtain the key whose value is max and print it.

    largest_hour = max(example_dict.items(), key=operator.itemgetter(1))[1]
    
    highest_key = []
    for person, hours in example_dict.items():
        if hours == largest_hour:
            highest_key.append((person, hours))
    
    for pair in highest_key:
    
        print('Person with largest hours is:', pair[0])