Create averages from a list from .txt file? - python

classs = input("Class [1, 2 or 3] - ")
if clas
data = f.readlines()
for le:
print(line)
found = True
if found == False:
print("False")
Here is a typical printed output:
John = 10
John = 6
John = 4
I need to be able to create an average just by using the 10, 4, 6 as I need to know a way to isolate the rest and allow the numbers to proceed inorder to create the average score.

If the format of each line is the same, you can use string.split and cast to int:
classs = input("Class [1, 2 or 3] - ")
l = []
if classs =='1':
name = input("What is your name? - ")
datafile = '1.txt'
found = False
with open(datafile, 'r') as f:
data = f.readlines()
for line in data:
if name in line:
print(line)
l.append(int(line.split()[2]))
found = True
if found == False:
print("False")
Then go through the list of numbers and get the average, something like:
total = 0
num = 0
for x in l:
total = total + x
num = num + 1
print(total/num)

one way would be to extract the last 3 numbers for each player from your list (i'm assuming you only need 3, if not this code can be altered for more)
Class = input("Class: ")
dataList = []
file = open('class ' + str(Class) + '.txt', "r")
for line in file:
count = 0
record = line
studentList = record.split(': ')
score = studentList[1].strip('\n')
studentList = [studentList[0], score]
if len(dataList) == 0:
dataList.append(studentList)
else:
while count < len(dataList):
if studentList[0] == dataList[count][0]:
if len(dataList[count]) == 4:
dataList[count][3] = dataList[count][2]
dataList[count][2] = dataList[count][1]
dataList[count][1] = score
break
dataList[count].append(score)
break
elif count == len(dataList) - 1:
dataList.append(studentList)
break
count = count + 1
this will give you a 2D array. each smaller array within will conatin the persons name at index 0 and there three numbers at indecies 1,2 and 3. now that you have these, you can simply work out the average.
AverageScore = []
# this is the array where the student' record (name and highest score) is saved
# in a list
count = 0
while count < len(dataList):
entry = []
# this is whre each student name and score will be temporarily held
entry.append(dataList[count][0])
# this makes it so the array 'entry' contains the name of every student
Sum = 0
frequency = len(dataList[count])
incount = 1
while incount < frequency:
Sum = Sum + int(dataList[count][incount])
incount = incount + 1
average = Sum / (frequency-1)
entry.append(average)
AverageScore.append(entry)
# this appends the name and average score of the student to the larger array
# 'AverageScore'
count= count + 1
# the count is increased so the process is repeated for the next student
AverageSorted = sorted(AverageScore,key=lambda l:l[1], reverse=True)
# http://stackoverflow.com/questions/18563680/sorting-2d-list-python
# this is code i obtained through someone else's post which arranges the array in descending
# order of scores
count2 = 0
while count2 < len(AverageSorted):
print(AverageSorted[count2][0], ':', AverageSorted[count2][1])
count2 = count2 + 1
# this formats the array so it prints the elements in a list of each student's
# name and score
Long winded and inefficient, but its the best i can do with my small knowledge of python :)

If this is the content of 1.txt:
John = 1
Joe = 3
John = 7
Joe = 9
Bob = 3
Joe = 8
John = 2
Bob = 9
Roger = 13
Replace your "with" statement with this:
name = "John"
_class = 1
with open("%s.txt" % _class, "r") as out:
lines = out.readlines()
scores = []
for line in lines:
if name in line:
# "strip" without arguments strips out all beginning
# and trailing white-space (i.e. " ", "\n", "\r").
line = line.strip()
score = int(line.split(" = ")[1])
scores.append(score)
# If there isn't any scores in this list, then there was no user
# data.
if scores:
# Use python built-in sum to sum the list of scores and
# divide the result by the number of scores gives you the average.
average = sum(scores) / len(scores)
print "%s's average score is %.1f out of %d game(s)." % (
name, average, len(scores))
else:
print "User %s not found." % name

Related

how can i compare within a group in python without using "import" or pandas?

so I currently have a data in csv file that looks like this:
class name. grade
grade 5 john. 4
grade 5 elias 5
grade 6 john 6
grade 6 elias 4
and I need to compare the grades of john and elias for each grade
and print like this:
class winner
grade 5 elias
grade 6 john
I am not allowed to use any import or pandas
this is what I have so far:
data = dict()
with open("summary.csv", "r", encoding="cp949") as f:
heads = f.readline().split("\t")
for line in f:
class,name,grade = line.split(',')
data[class] = data.setdefault(state, dict())
I am not sure how to proceed afterward.
In order to correctly split the data, I suppose that they are comma-separated in the CSV file:
class name. grade
grade 5,john.,4
grade 5,elias,5
grade 6,john,6
grade 6,elias,4
Then here is a solution to retrieve the best students for each class. It uses 2 dictionaries: one for the link classname/student name, the other for the link class name/best grade.
data = dict()
grades = dict()
with open("summary.csv", "r", encoding="cp949") as f:
heads = f.readline().split("\t")
for line in f:
# Ignore empty lines
if not line.strip():
continue
# The split can be encased in a try/except block
# to deal with lines without 2 commas
classname, name, grade = line.split(',')
# Ignore line where last element is not a integer
if not grade.strip().isdigit():
continue
# Convert string to integer
grade = int(grade.strip())
# Update best name if the current grade is higher
# than the stored one in grades
if grade > grades.get(classname.strip(), -1):
data[classname.strip()] = name.strip()
grades[classname.strip()] = grade
print("class\twinner")
for classname, best in data.items():
print("{}\t{}".format(classname, best))
Here's another approach that follows from your code and uses a dictionary of lists to store the winners. First loop reads the file and stores as a list. Second loop iterates through the list to pick winners.
data = dict()
l = []
with open("yas.csv", "r", encoding="cp949") as f:
heads = f.readline().split("\t")
for line in f:
cl,name,grade = line.split(',')
# append to a list
l.append([cl, name, grade])
for x in l:
# get rid of line break if necessary
x = [sub.replace('\n', '') for sub in x]
gradekey = x[0]
name = x[1]
score = int(x[2])
# data is dictionary of lists, containing winners only
if gradekey in data.keys():
# if we have a new winner, put it in the dictionary
data[gradekey] = [name, max(data[gradekey][1], score)]
else:
# this is the first one for this grade, enter it as the current winner
data[gradekey] = [name, score]
print('Winners are', data)
Output is:
Winners are {'grade 5': ['elias', 5], 'grade 6': ['elias', 6]}
let us first specifiy yas.csv file to be:
class,name,grade
grade 5,john.,4
grade 5,elias,5
grade 6,john,6
grade 6,elias,4
Then the could would be
data = dict()
with open("yas.csv", "r", encoding="cp949") as f:
heads = f.readline()
for line in f:
a = line.split(',')
if a[0] in data.keys():
if data[a[0]][1] < a[2]:
data[a[0]] = (a[1], a[2])
else:
data[a[0]] = (a[1], a[2])
# output
print('class', 'winner')
for k, v in data.items():
print(k, v[0])
The output is
class winner
grade 5 elias
grade 6 john

Summing and Average using python

I have written a code that extracts floating point numbers from a
text file and produces a list of the numbers.
My challenge is summing the consecutive numbers and finding the
average of the numbers.
I am not allowed to use the sum function and I am new to python ..
this the code I have written so far ,
what can I do to add through the list
fh = open(fname)
for line in fh:
if line.startswith("X-DSPAM-Confidence:") : continue
# print(line)
count = 0
for line in fh:
if line.startswith("X-DSPAM-Confidence:"):
count = count + 1
# print(count)
for line in fh:
if line.startswith("X-DSPAM-Confidence:"):
# print(line)
xpos = line.find(' ')
# print(xpos)
num = line[xpos : ]
# print(float(num))
fnum = float(num)
# print(fnum)
total = 0
for i in fnum:
total += int(i)
print(total)
Error:"float object not iterable on line 24" ... line 24 is the 4th for loop
First an open file is iterable only once, and your code shows 4 loops starting with for line in fh:. After first loop, the file pointer will reach the end of file, and the following loops should immediately return. For that reason with should be prefered.
Next somewhere in the loop you get a float value in fnum. Just initialize total before starting the loop, and add fnum when you get it:
total = 0
with open(fname) as fh:
for line in fh:
if line.startswith("X-DSPAM-Confidence:"):
# print(line)
xpos = line.find(' ')
# print(xpos)
num = line[xpos : ]
# print(float(num))
fnum = float(num)
# print(fnum)
total += fnum
# print(total)
with ensures that the file will be cleanly closed at the end of the loop.
fnum is a float. It's not an array, therefore it's not iterable and cannot be iterated in a for loop.
You probably don't need an array to determine the total and the average:
fname = "c:\\mbox-short.txt"
fh = open(fname)
count = 0
total = 0
for line in fh:
if line.startswith("X-DSPAM-Confidence:"):
xpos = line.find(' ')
num = line[xpos : ]
fnum = float(num)
total += fnum
count += 1
print("Total = " + str(total))
print("Average = " + str(total / count))
print("Number of items = " + str(count))
You don't have to use startsWith in this case. Better to use split for each line of the file. Each line will split all the words to a list. Then using the indexes you look for, X-DSPAM-Confidence:. If it exists then take the corresponding value of interest. In this case it is index number 1. Below is the code:
total = 0
number_of_items = 0
with open("dat.txt", 'r') as f:
for line in f:
fields = line.split()
if fields != []:
if fields[0] == "X-DSPAM-Confidence:":
number_of_items += 1
total += float(fields[1])
print(total)
print(number_of_items)
avg = (total/number_of_items)
print(avg)
I saved your data in a text file names, "dat.txt".
Hope it helps !!!

Calculating the totals of odd and even numbers from a file in Python

def main():
infile = open('numbers.txt','r')
evenTotal = 0
oddTotal = 0
line = infile.readline()
while line != '':
total += int(line)
line = infile.readline()
print('The total for the even numbers is',evenTotal)
print('The total for the odd numbers is',oddTotal)
infile.close()
print('All done!')
main()
I trying to make it so that the program reads the numbers from a file in its directory and then separates, calculates and displays the total of the two sets. The thing I am having trouble with is the part in the middle with the identification of the odds and the evens. I do know that the while loop I have written in the middle calculates the total but I don't know how to modify it to make it so it does what I want it to do.
from itertools you can use the partition recipe to partition into even and odd and return the sum of those
from itertools import ifilterfalse,imap,ifilter,tee
def partition(pred, iterable):
'Use a predicate to partition entries into false entries and true entries'
# partition(is_odd, range(10)) --> 0 2 4 6 8 and 1 3 5 7 9
t1, t2 = tee(iterable)
return ifilterfalse(pred, t1), ifilter(pred, t2)
def is_odd(x):
return bool(x%2)
list_of_ints = imap(int,filter(lambda x:x.strip().isdigit(),infile))
odds, evens= partition(is_odd,list_of_ints)
print sum(evens),sum(odds)
it will likely be a little bit slower than freddies answer ...
but it is a good pattern to know
or as #JonClements pointed out in chat
r = range(11)
d = dict.fromkeys([0, 1], 0)
for i in r: d[i % 2] += i
is a neat way to do it
In order to check if a number is odd or even, you should use the modulus operator.
if an integer is evenly divisible by 2, it will be even, otherwise, it is odd.
So...
while line != '':
if int(line) % 2 == 0:
evenTotal += int(line)
else
oddTotal += int(line)
line = infile.readline()
use this for even number
def even_numbers(maximum):
return_string = ""
for x in range(2,maximum+1,2):
return_string += str(x) + " "
return return_string.strip()
# With this program in Python you will check a document for even and odd numbers and
# also it skips any text
# It also writes 2 extra files Oddfile and Evenfile
import re
fhand = open('numbers.txt') # file with numbers odd/even or even filled with text
text = fhand.read()
y = re.findall('[0-9]+', text)
sumeven = 0
sumodd = 0
Even = []
Odd = []
Oddfile=open('Oddfile.txt','w')
Evenfile=open('Evenfile.txt','w')
for number in y:
if (int(number) % 2) == 0:# Checks if the number is even
sumeven = sumeven + int(number)
Even.append(int(number))
Evenfile.write(str(number) + '\n')
if (int(number) % 2) == 1:# Checks if the number is odd
sumodd = sumodd + int(number)
Odd.append(int(number))
Oddfile.write(str(number) + '\n')
print("Even List is : ", Even)
print("Odd List is : ", Odd)

How to add more than one integer to a name in a python dictionary?

This is my code and I need to work out the average score for each student but this part of the code is incorrect.It is the part with the stars that I need to fix
while choice == 'av'.lower():
if schClass == '1':
schClass = open("scores1.txt", 'r')
li = open("scores1.txt", 'r')
data = li.read().splitlines()
for li in data:
name = li.split(":")[0]
score = li.split(":")[1]
**if name not in diction1:
diction1[name] = score
elif name in diction1:
diction1[name] = int(score) + diction1[name]**
How does the file look like?
A: 10
B: 10
A: 20
B: 12
or
A: 10 20
B: 10 12
This solution works with both formats.
First, build a dict of lists with all scores:
all_scores = {}
while choice == 'av':
if schClass == '1':
with open("scores1.txt", 'r') as f:
for line in f:
name, scores = li.split(':', 1)
name_scores = all_scores.setdefault(name, [])
for score in scores.split():
name_scores.append(int(score))
Then calculate the average (convert to sum to float in order to get exact average):
averages = {name: float(sum(scores)) / len(scores)
for name, scores in all_scores.iteritems()}
Your question is unclear; in other words, what do you mean with adding more than one integer to a dictionary key? This part is confusing because your code
diction1[name] = int(score) + diction1[name]**
seems to imply you'd like to add a string (score) to an integer (int(score)), which is impossible. If it's to add them side by side in a list so that, given a score of '4', the result is ['4', 4], then all you have to do is change the last few lines to this.
if name not in diction1:
diction1[name] = [score, int(score)]
Also, eumiro's other changes to your code are good advice, so keep them in mind and read the docs if you're unsure of how any of it works.
Make diction1 hold a list.
if name not in diction1:
diction1[name] = [score]
else:
diction1[name].append(int(score))

Calculating average of numbers in a file

So what I have to do is figure out how to ask a user for a a text file and output the average of all the numbers. By tinkering around I have figured out how to find the average of a list i made but not sure how to do a list that the user give me. This is what I have right now:
with open('average', 'wt') as myFile:
myFile.write('3\n')
myFile.write('45\n')
myFile.write('83\n')
myFile.write('21\n')
with open('average', 'rt') as myFile:
total, n = 0, 0
for line in myFile:
total += int(line)
n += 1
print(float(total) / n)
Supposing that there is one number on each line of the file:
with open(input('Filename: '), 'r') as f:
numbers = [int(a.strip()) for a in f]
print('Average is {}'.format(sum(numbers)/len(numbers)))
Something like this?
import string
fileName = raw_input("What file name: ")
lines = []
try:
file = open(fileName)
lines = file.readlines()
file.close()
except:
print "Unable to open file"
sum = 0
values = 0
if(len(lines) > 0):
for line in lines:
value = 0
try:
value = int(string.strip(line))
except ValueError:
pass
if(value != 0):
sum = sum + value
values += 1
print "Average = %f for %d lines, sum = %f"%(sum/values,values,sum)
else:
print "No lines in the file"
NOTE: This assumes one number per line. It will not count blank lines or lines that have text. Other than that, junk on the lines or a bad file should not cause an exception, etc.
This was the test file (there are blank lines):
10
20
30
40
50
23
5
asdfadfs
s
And the output:
What file name: numbers.txt
Average = 25.000000 for 7 lines, sum = 178.000000

Categories