0

I had stuck with this task and really need some help.

I have a data in the text file:

John 46.5 Sam 62 Steve 45.5 Nigel 67.1 Karen 55
Henry 55 Alex 42 Graham 82 Hannah 56 Nicola 66
Ruth 81 Carl 90 Ben 66.8 

And need to Write a program that can read the data from the text file and output each nameand number pair on a new line like this:

>>>
John : 46.5
Sam : 62
Steve : 45.5
Nigel : 67.1
Karen : 55
Henry : 55
Alex : 42
Graham : 82
Hannah : 56
Nicola : 66
Ruth : 81
Carl : 90
Ben : 66.8
AVERAGE: 62.684615384615384
>>> 

I can output the text from the file and separate the elements it contains, but I can't set up the correct output as it is specified in the condition.


f = open("grades.txt", "r")
d = f.read()
f.close()
print(d)
print()

d = d.splitlines()
print(d)
for line in d:
    print(line)
    line = line.split()
    print (line)
    
print()

If you can give me some advice and help me solve this task, I will be very grateful

Thanks in advance

tab
  • 25
  • 4

2 Answers2

0
  1. We can open the file and read its contents via a combination of a with statement and open. Note that we don't need the "r" argument to it, because it defaults to "r" if no argument is passed.
  2. We can then split the read contents of the file using str.split which defaults to splitting on all whitespace when no arguments are provided.
  3. We then initialise a cumulative sum to zero before you iterate through the list.
  4. We then iterate through the list you created previously with step size 2, so i is always even. This means that split_text[i] is always a name, and split_text[i+1] is always a number.
  5. Within your loop, we can unpack these into two variables by using slicing.
  6. Still within your loop, we output the name and the value using print and an fstring.
  7. Finally within your loop, we increment the cumulative sum. However, since we can't increment numeric values by strings, we must first convert it to a numeric value. Since some of the values given above are floats, we must use float instead of int, because if we used the latter it would raise a ValueError.
  8. Once we leave your loop, we calculate the number of values, which is half the len of the split contents of the file.
  9. Finally, we calculate your average by dividing the sum by the number of values and printing that.
    # Open the file and read the contents
    with open("grades.txt") as file:
        # split the contents on whitespace
        split_text = file.read().split()

    # Initialise the cumulative sum to zero
    cumulative_sum = 0

    # Iterate through the list with step size 2
    for i in range(0, len(split_text), 2):
        # Use slicing and multiple assignment to get the name and the value
        name, value = split_text[i:i+2]

        # Output the name and the value
        print(f'{name} : {value}')

        # Increase the cumulative sum
        cumulative_sum += float(value)

    # Output the final average
    n = len(split_text)/2
    print('AVERAGE:', cumulative_sum/n)

Output:

John : 46.5
Sam : 62
Steve : 45.5
Nigel : 67.1
Karen : 55
Henry : 55
Alex : 42
Graham : 82
Hannah : 56
Nicola : 66
Ruth : 81
Carl : 90
Ben : 66.8
AVERAGE: 62.684615384615384
General Grievance
  • 4,555
  • 31
  • 31
  • 45
Mous
  • 953
  • 3
  • 14
-1

Simple Solution:

You can read the text as lines and then split it into an array of words. Try this:

values = []
with open('grades.txt') as f:
  lines = f.readlines()
  for i in lines:
    data = i.strip().split(' ')
    counter = 0
    for j in data:
      if counter % 2 == 0:
        string = ''
        string += j + ' : '
      else:
        values.append(float(j))
        string += j
        print(string)
      counter += 1
  print('AVERAGE:',sum(values)/len(values))
Jordy
  • 1,802
  • 2
  • 6
  • 25
  • This code doesn't work. It incorrectly calculates the average as 62.638461538461534 when it is 62.684615384615384, as shown in my answer and in the desired output OP posted. – Mous Feb 24 '23 at 11:26
  • Thanks for the correction! I've updated the code above. – Jordy Feb 24 '23 at 16:07