Home > Enterprise >  Problem to find the length and average of a list array in python
Problem to find the length and average of a list array in python

Time:11-17

I try to write a program that calculates the average length of words stored in a text file, one on each line. More explanatory the program will read the words in the file, find their length and at the end calculate the average length. The file includes the follow words: Book,List,Python,Masterpiece,National etc. About all of these I wrote the follow lines of code:

import requests
import os
import math


f = open('C:/tt.txt','r',encoding='utf-8')

#for list in f:
        #f = list.split() 

for list in f:
        a=len(list)
        #print(len(list))
        print(a)
        #b=sum(len(list))
avg=sum(a)/coun(list) #find the average

When program is running the result of the words length is ok but not with the proper order (for example 5,7,12,9 but it must be 9,12,5...).An other program is that the contents of the txt document can not splitting (look at the code comment).The result of the compiler is :Traceback (most recent call last): File "C:\Users\pliroforiki-sox2\Desktop\exercises\4_07.py", line 17, in avg=sum(list)/count(a) #find the average TypeError: unsupported operand type(s) for : 'int' and 'str'enter image description here

CodePudding user response:

How's this?

total = 0
word_count = 0
with open('C:/tt.txt','r',encoding='utf-8') as f:
    for line in f:
        word_length = len(line.strip())
        print(word_length)
        total  = word_length
        word_count  = 1
print(total / word_count)

Note that I also use the "with open() as f:" syntax which is better practice. This handles the file cleanup for you automatically.

  • Related