Find Min and Max from Text File - Python - python

I need to find the minimum and max value from this list of data. I can get the maximum but the minimum. The text file has a lot of data so I decided to upload it here: https://www.dropbox.com/s/u5ov5zij9v5fumt/project05.data.txt?dl=0
Input
try:
file_name = input("Enter the name of an input file ")
input_file = open( file_name, "r" )
header=input_file.readline()
count=0
total=0
largest_num=0
smallest_num=0
michigan=""
for line in input_file:
output=float(line[67:71].rstrip())
total += output
count +=1
if largest_num<= output:
largest_num = output
if smallest_num >= output:
smallest_num = output
if line[0:17].rstrip() == "Michigan":
state=(line[0:17])
number=(line[67:75])
print("\nState with the smallest MMR vaccation rate:")
print(" with a rate of")
print("\n State with largest MMR vaccination rate:" )
print(" with a rate of")
print("\nThe calculated average vaccination rate is",round(total/count,1))
print("")
print("Michigan MMR vaccination rate is", number)
input_file.close()
except FileNotFoundError:
print("Error: file not found")
file_name = input("Enter the name of an input file ")
input_file = open( file_name, "r" )

List comprehensions are your friends.
numbers = [float(line[67:71].rstrip()) for line in input_file]
largest_num = max(numbers)
smallest_num = min(numbers)
total = sum(numbers)
count = len(numbers)

Related

I'm getting a ValueError: cannot convert string to float: ".". What is going on?

I am trying to write a function that takes in a file with numerical values, total them all up while excluding all numbers with a letter, and find the average. However, when I try to convert a number like "3.9" to float form, I get the ValueError: cannot convert string to float: ".". I know that if I just did a straight conversion of "3.9" to float form via float("3.9") type casting it would work.
def averageSpeed():
count = 0
total = 0
stripLst = 'abcdefghijklmnopqrstuvwxyz$'
while count < 2:
try:
filename = input("Enter a file to process: ")
instance = open(filename, "r")
content = instance.readlines()
for line in content:
lineSplit = line.split()
for element in lineSplit:
for letter in element:
for character in stripLst:
if letter == character:
lineSplit.remove(element)
for line in content:
for element in line:
if float(element) > 2:
total += float(element)
print(lineSplit)
average = total / count
print(average)
break
except (FileNotFoundError):
print("That file does not exist.")
count += 1
filename = input("Enter a file name that exists: ")
averageSpeed()
File contents:
35.2
1.8
65.6
67.9z
70.2
73.2 a3.9 65.6 69.8
6$4.9
54.9
Oops, just fixed my own question with the code below:
def averageSpeed():
count = 0
total = 0
stripLst = 'abcdefghijklmnopqrstuvwxyz$'
while count < 2:
try:
filename = input("Enter a file to process: ")
instance = open(filename, "r")
content = instance.readlines()
for line in content:
print(line)
print()
for line in content:
lineSplit = line.split()
for element in lineSplit:
for letter in element:
for character in stripLst:
if letter == character:
lineSplit.remove(element)
for element in lineSplit:
if float(element) > 2:
total += float(element)
count += 1
print(lineSplit)
average = total / count
print("The total of the speeds of {} excluding all speeds with lettres in them is {}.".format(filename, total))
print("The total number of speeds in {} without letters is {}.".format(filename, count))
print("The average of the speeds of {} excluding all speeds with letters in them is {}.".format(filename, average))
break
except (FileNotFoundError):
print("That file does not exist.")
count += 1
filename = input("Enter a file name that exists: ")
averageSpeed()

Why is my function not printing the try-except-else result?

What is wrong with my code? I am not being able to retrieve data about the age range. I am working with a CSV file but having problems with the try-except-else suite. I am trying to find the average data for a given age range but am not being able to as nothing is printing.
def calculator(min_age, max_age):
file = open(r"C:\Users\alisha\OneDrive\Desktop\programming\data.csv")
data = file.read()
file.close()
#data processing
lines = data.split("\n")
del lines [-1]
#18 lines
line1 = lines[1].split(",")
line2 = lines[2].split(",")
line3 = lines[3].split(",")
line4 = lines[4].split(",")
line5 = lines[5].split(",")
line6 = lines[6].split(",")
line7 = lines[7].split(",")
line8 = lines[8].split(",")
line9 = lines[9].split(",")
line10 = lines[10].split(",")
line11 = lines[11].split(",")
line12 = lines[12].split(",")
line13 = lines[13].split(",")
line14 = lines[14].split(",")
line15 = lines[15].split(",")
line16 = lines[16].split(",")
line17 = lines[17].split(",")
line18 = lines[18].split(",")
processed = [line1, line2, line3, line4, line5, line6, line7, line8, line9, line10, line11, line12, line13, line14, line15, line16, line17, line18]
#obtain height and weight columns
age = []
for line in processed:
age.append(line[2])
min_value = min(age)
max_value = max(age)
target_weight = []
target_height = []
for line in processed:
if int(line[2]) >= min_age and int(line[2]) <= max_age:
target_weight.append(line[4])
target_height.append(line[3])
try:
calc = ((target_weight/len(target_weight)) / (target_height / len(target_height))**2 )*703
except:
if int(min_age) < int(min_value):
print("Minimum age value too small. Try Again.")
elif int(max_age) > int(max_value):
print("Maximum age value too large. Try Again.")
else:
print(f"The average for the given age range {max_age} to {min_age} is {calc}.")
sounds like your teacher wants you to create custom error classes to throw, try this:
class ValueTooHighError(Error):
pass
class ValueTooLowError(Error):
pass
file_obj = open(r"C:\Users\ahana\OneDrive\Desktop\intro toprogramming\assignment_8\patient_data.csv")
data = file_obj.read()
file_obj.close()
#----left out some code for conciseness----#
min_value = min(age)
max_value = max(age)
target_weight = []
target_height = []
for line in processed:
try:
if int(line[2]) >= min_age and int(line[2]) <= max_age:
target_weight.append(line[4])
target_height.append(line[3])
else:
if(int(line[2])<min_age):
raise ValueTooLowError
else:
raise ValueTooHighError
except:
ValueTooLowError:
print("Minimum age value too small. Try Again.")
ValueTooHighError:
print("Maximum age value too large. Try Again.")
bmi = ((sum(target_weight)/len(target_weight)) / (sum(target_height) / len(target_height))**2 )*703
print(f"The average BMI for the given age range {max_age} to {min_age} is {bmi}.")
There is a lot going on here, first I will address your actual question with the try-except block. I believe you want the except code to run when age value is out of range, but you need to actually generate an exception for the try statement to catch:
def calcBMI(minimum, maximum, val):
if val<minimum or val>maximum:
raise ValueError
# do stuff
try:
bmi = calcBMI(min_age, max_age, value)
except ValueError:
print("Error")
else:
print(bmi)
There is also a lot of bad form going on, you are using 18 separate near-identical lines to do something that only takes one! Those 18 lines where you fill up the processed list can be written as:
processed = [line.split(",") for line in lines]
Another thing is you run the same for-loop 3 times to populate age, height and weight lists. You could do this in one like this:
for line in processed:
age.append(line[2])
height.append(line[3])
weight.append(line[4])

How to align two columns perfectly in python?

I have an assignment where we have to read the file we created that has the test names and scores and print them in columns. Getting the data and displaying it, along with the average, is no problem, but I do not understand how to align the scores to the right in the output column. In the output example the scores line up perfectly to the right of the "SCORES" column. I can format their width using format(scores, '10d') as an example, but that's always relative to how long the name of the test was. Any advice?
def main():
testAndscores = open('tests.txt', 'r')
totalTestscoresVaule = 0
numberOfexams = 0
line = testAndscores.readline()
print("Reading tests and scores")
print("============================")
print("TEST SCORES")
while line != "":
examName = line.rstrip('\n')
testScore = float(testAndscores.readline())
totalTestscoresVaule += testScore
## here is where I am having problems
## can't seem to find info how to align into
## two columns.
print(format(examName),end="")
print(format(" "),end="")
print(repr(testScore).ljust(20))
line = testAndscores.readline()
numberOfexams += 1
averageOftheTestscores = totalTestscoresVaule / numberOfexams
print("Average is", (averageOftheTestscores))
#close the file
testAndscores.close()
main()
You just have to store each name and score in a list, then calculate the longest name, and use this length to print space for shorter name.
def main():
with open('tests.txt', 'r') as f:
data = []
totalTestscoresVaule = 0
numberOfexams = 0
while True:
exam_name = f.readline().rstrip('\n')
if exam_name == "":
break
line = f.readline().rstrip('\n')
test_score = float(line)
totalTestscoresVaule += test_score
data.append({'name': exam_name, 'score': test_score})
numberOfexams += 1
averageOftheTestscores = totalTestscoresVaule / numberOfexams
longuest_test_name = max([len(d['name']) for d in data])
print("Reading tests and scores")
print("============================")
print("TEST{0} SCORES".format(' ' * (longuest_test_name - 4)))
for d in data:
print(format(d['name']), end=" ")
print(format(" " * (longuest_test_name - len(d['name']))), end="")
print(repr(d['score']).ljust(20))
print("Average is", (averageOftheTestscores))
main()

Opening a file for append error

I'm trying to open a file for appending, but I keep getting the "except" portion of my try/except block, meaning there is some sort of error with the code but I can't seem to find what exactly is wrong with it. It only happens when I try to open a new file like so:
results = open("results.txt", "a")
results.append(score3)
Here's my full code:
import statistics
# input
filename = input("Enter a class to grade: ")
try:
# open file name
open(filename+".txt", "r")
print("Succesfully opened", filename,".txt", sep='')
print("**** ANALYZING ****")
with open(filename+".txt", 'r') as f:
counter1 = 0
counter2 = 0
right = 0
answerkey = "B,A,D,D,C,B,D,A,C,C,D,B,A,B,A,C,B,D,A,C,A,A,B,D,D"
a = []
# validating files
for line in f:
if len(line.split(',')) !=26:
print("Invalid line of data: does not contain exactly 26 values:")
print(line)
counter2 += 1
counter1 -= 1
if line.split(",")[0][1:9].isdigit() != True:
print("Invalid line of data: wrong N#:")
print(line)
counter2 += 1
counter1 -= 1
if len(line.split(",")[0]) != 9:
print("Invalid line of data: wrong N#:")
print(line)
counter2 += 1
counter1 -= 1
counter1 += 1
#grading students
score = len(([x for x in zip(answerkey.split(","), line.split(",")[1:]) if x[0] != x[1]]))
score1 = 26 - score
score2 = score1 / 26
score3 = score2 * 100
a.append(score3)
# results file
results = open("results.txt", "a")
results.write(score3)
# in case of no errors
if counter2 == 0:
print("No errors found!")
# calculating
number = len(a)
sum1 = sum(a)
max1 = max(a)
min1 = min(a)
range1 = max1 - min1
av = sum1/number
# turn to int
av1 = int(av)
max2 = int(max1)
min2 = int(min1)
range2 = int(range1)
# median
sort1 = sorted(a)
number2 = number / 2
number2i = int(number2)
median = a[number2i]
median1 = int(median)
# mode
from statistics import mode
mode = mode(sort1)
imode = int(mode)
# printing
print ("**** REPORT ****")
print ("Total valid lines of data:", counter1)
print ("Total invalid lines of data:", counter2)
print ("Mean (average) score:", av1)
print ("Highest score:", max2)
print("Lowest score:", min2)
print("Range of scores:", range2)
print("Median Score:", median1)
print("Mode score(s):", imode)
results.close()
except:
print("File cannot be found.")
I don't think there is a method called append for writing into file. You can use the write or writelines method only to write. As you already opened the file with append permissions. It wont change the old data and will append the text to the file.
f=open('ccc.txt','a')
f.write('Hellloooo')
f.close()
Hope it helps.

wrap all lines that are longer than line length

I am writing a program that limits each line to a certain length.
this is what i got so far, i am almost done but i still need to cut each line, but i cant figure it out.
def main():
filename = input("Please enter the name of the file to be used: ")
openFile = open(filename, 'r+')
file = openFile.read()
lLength = int(input("enter a number between 10 & 20: "))
while (lLength < 10) or (lLength > 20) :
print("Invalid input, please try again...")
lLength = int(input("enter a number between 10 & 20: "))
wr = textwrap.TextWrapper()
wraped = wr.wrap(file)
print("Here is your output formated to a max of", lLength, "characters per line: ")
wr.width = lLength
wr.expand_tabs = True
for lines in wraped:
print(lines)
Edit:
def main():
filename = input("Please enter the name of the file to be used: ")
openFile = open(filename, 'r')
file = openFile.read()
lLength = int(input("enter a number between 10 & 20: "))
while (lLength < 10) or (lLength > 20) :
print("Invalid input, please try again...")
lLength = int(input("enter a number between 10 & 20: "))
if (lLength > 10) or (lLength < 20):
print("\nYour file contains the following text: \n" + file)
#=========================================================================
wr = textwrap.TextWrapper(width=lLength)
wraped = wr.wrap(file)
print("\n\nHere is your output formated to a max of", lLength, "characters per line: ")
for lines in wraped:
print(lines)
main()
an example of what the output SHOULD be is this.
If the file specified contains this text:
hgytuinghdt #here the length is 11
ughtnjuiknshfyth #here the length is 16
nmjhkaiolgytuhngjuin #here the length is 20
and the lLength is specified to 15 then this should print out:
hgytuinghdt
ughtnjuiknshfyt
h
nmjhkaiolgytuhng
juin
wr = textwrap.TextWrapper() should be wr = textwrap.TextWrapper(width=length, expand_tabs=True)
You should then remove wr.width = lLength and wr.expand_tabs = True. They should have been run before wr.wrap() was called, but since one can set it using keyword arguments in the TextWrapper constructor as shown at the very top, they can be removed.
PS: for lines in wraped: print(lines) can be replaced with print(wraped) if you use TextWrapper.fill.
Try this:
line = 'nmjhkaiolgytuhngjuin'
n = 5 # set the width here
a = [line[i:i+n] for i in range(0, len(line), n)]
print ("\n".join(a))
This might help you:
def wrap(f,n):
fi=open(f,"w+")
rl=fi.readlines()
for i in range(0,len(rl)):
if len(rl[i]) > n:
fi.write(rl[i][:n] +"\n" + rl[i][n:])
fi.Close()
else:
fi.write(rl[i])
fi.close()

Categories

Resources