Home > Software engineering >  Finding max values in a text file read in using Python
Finding max values in a text file read in using Python

Time:12-03

I have a text file containing only numbers. There are gaps in the sets of numbers and the problem asks that the file is read through, adds the numbers within each group then finds the top three values in the list and adds them together. I've found the way to read through the file and calculate the sum of the largest set but cannot find the second or third.

I've pasted my code here:my coding attempt and my results text file content here: List of values in the text file

CodePudding user response:

I hope I have understood the question correctly, this script should calculate the sum of integers in each group (each new integer group is defined by a blank link in the numbers file).

# Open the file for reading
with open('numbers.txt', 'r') as f:
  # Read the file line by line
  lines = f.readlines()

# Initialize a list to store the sum of each group of numbers
sums = []

# Initialize a variable to store the current group of numbers
numbers = []

# Iterate over the lines in the file
for line in lines:
  # If the line is empty, it marks the end of a group of numbers
  if line.strip() == '':
    # Calculate the sum of the numbers in the current group
    sums.append(sum(numbers))

    # Reset the list of numbers for the next group
    numbers = []
  else:
    # Split the line into a list of numbers
    numbers_on_line = line.split()

    # Convert the numbers from strings to integers
    numbers_on_line = [int(n) for n in numbers_on_line]

    # Add the numbers from the current line to the current group
    numbers.extend(numbers_on_line)

# Sort the list of sums in descending order
sums.sort(reverse=True)

# Calculate the sum of the top three values
result = sums[0]   sums[1]   sums[2]

# Print the result
print(result)

The code will check if each line is empty, and if it is, it will calculate the sum of the numbers in the current group and reset the list of numbers for the next group. If the line is not empty, it will split the line into a list of numbers, convert them from strings to integers, and add them to the current group.

The top 3 sum values are then calculated by sorting the list and selecting the top 3 values.

Hope this helps!

CodePudding user response:

Create a list to store the group totals.

Read the file a line at a time. Try to convert each line to int. If that fails then you're at a group separator so append zero to the group_totals list

Sort the list and print the last 3 items

FILENAME = '/Users/dan/Desktop/day1 copy.txt'

group_totals = [0]

with open(FILENAME) as data:
    for line in data:
        try:
            group_totals[-1]  = int(line)
        except ValueError:
            group_totals.append(0)
    print(sorted(group_totals)[-3:])

Output:

[740, 1350, 2000]

Note:

This code implicitly assumes that there are at least 3 groups of values

  • Related