87.3k views
0 votes
A file named numbers.txt contains an unknown number of lines, each consisting of a single positive integer. Write some code that reads through the file, ignoring those value that are not bigger than the maximum value read up to that point. The numbers that are NOT ignored are added, and their sum stored in a variable called runsum.

1 Answer

3 votes

Answer:

  1. with(open("numbers.txt")) as file:
  2. data = file.readlines()
  3. runsum = 0
  4. largest = 0
  5. for x in data:
  6. if(int(x) > largest):
  7. largest = int(x)
  8. runsum += largest
  9. print(runsum)

Step-by-step explanation:

The solution code is written in Python 3.

Firstly, open a filestream for numbers.txt (Line 1) and then use readlines method to get every row of data from the text files (Line 2).

Create a variable runsum to hold the running sum of number bigger than the maximum value read up to that iteration in a for loop (Line 3).

Use a for loop to traverse through the read data and then check if the current row of integer is bigger than the maximum value up to that point, set the current integer to largest variable and then add the largest to runsum (Line 6 - 9).

At last display the runsum to console terminal (Line 11).

User Rohan Khude
by
5.3k points