How to I make this stop? - python

Right now, it reads off a txt file and gives me the sum per line. The problem is that it will print a line per line of numbers in my txt file (So say I my txt file has 25 different numbers, it will print "The accumulated total is:" 25 times, adding the last value to the next. I want only to print the total (one line). This is for a homework assignment.
def main ():
print()
print("This will add together the numbers on number.txt")
print()
total, error = getsum()
if not error:
total = getsum()
print ("The sum is", total)
def getsum ():
error = False
total = 0
try:
infile = open("Numbers.txt", "r")
line = infile.readline()
while line != "":
readnum = float(line)
total = readnum + total
line = infile.readline()
print("The accumulated total is", total)
file.close()
except IOError:
print ("ERROR")
error = True
except ValueError:
print ("ERROR")
error = True
if error:
sum5 = 0
else:
sum5 = total
return total, error, thesum
main ()

print sum(map(float,filter(lambda line:line.strip(),open("some.txt"))))
is much shorter ... or if you are concerned baout not closing the file
with open("some.txt") as f:
print sum(map(float,filter(lambda line:line.strip(),f)))

Related

Python program not working - simple mathematic function

cat Prog4CCM.py
numberArray = []
count = 0
#filename = input("Please enter the file name: ")
filename = "t.txt" # for testing purposes
file = open(filename, "r")
for each_line in file:
numberArray.append(each_line)
for i in numberArray:
print(i)
count = count + 1
def findMaxValue(numberArray, count):
maxval = numberArray[0]
for i in range(0, count):
if numberArray[i] > maxval:
maxval = numberArray[i]
return maxval
def findMinValue(numberArray, count):
minval = numberArray[0]
for i in range(0, count):
if numberArray[i] < minval:
minval = numberArray[i]
return minval
def findFirstOccurence(numberArray, vtf, count):
for i in range(0, count):
if numberArray[i] == vtf:
return i
break
i = i + 1
# Function calls start
print("The maxiumum value in the file is "+ str(findMaxValue(numberArray, count)))
print("The minimum value in the file is "+str(findMinValue(numberArray, count)))
vtf = input("Please insert the number you would like to find the first occurence of: ")
print("First occurence is at "+str(findFirstOccurence(numberArray, vtf, count)))
This is supposed to call a function (Find First Occurrence) and check for the first occurrence in my array.
It should return a proper value, but just returns "None". Why might this be?
The file reading, and max and min value all seem to work perfectly.
You forgot to add a return in the findFirstOccurence() function, in case the vtf response is not in the list and there is an error with adding one to the iterator and use break, the for loop will do that for you.
The correct code would look like this:
...
def findFirstOccurence(numberArray, vtf, count):
for i in range(0, count):
if numberArray[i] == vtf:
return i
# break # <==
# i = i + 1 # It's errors
return "Can't find =("
# Function calls start
print("The maxiumum value in the file is "+ str(findMaxValue(numberArray, count)))
print("The minimum value in the file is "+str(findMinValue(numberArray, count)))
vtf = input("Please insert the number you would like to find the first occurence of: ")
print("First occurence is at "+str(findFirstOccurence(numberArray, vtf, count)))
At a quick glance, the function findFirstOccurence miss return statement. If you want us to help you debug the code in detail, you may need to provide your test data, like t.txt

Having trouble with except function/ input validation

I am working on some code for a homework assignment where I have to take the numbers in a the file, calculate the sum of them all, the average and how many lines there are. This is what I've come up with so far
invalidEntry= True
#Input validation
while (invalidEntry) :
try:
total = 0
lines = 0
Validate= input("Please enter the name of the text file. : ")
if Validate ==("Random.txt") :
red= open( 'Random.txt', 'r')
for count in red:
strip = line.strip("\n")
lines += 1
average = total/200
total = total + int(count)
print("The number of lines is : ",lines)
print ("The total sum is : " ,total)
print("The average is :" , average
invalidEntry= False
except:
print("This isn't a valid file!")
I keep getting a syntax error for the except function and I'm unsure if I have the input validation set up properly. Any help would be appreciated.
Try with:
except Exception as err:
Try this, fixed a few bugs for you:
import os
total = 0
lines = 0
# Input the file
IfValidate = False
while IfValidate == False:
validate = input("Please enter the name of the text file: ")
if os.path.isfile(validate) == True:
IfValidate = True
# Open the file
f = open(validate, 'r')
# Read every line and make it a list
f = f.readlines()
for line in f:
# Strip of \n
strip = line.strip("\n")
# Make the number a number
num = int(strip)
lines += 1
average = total / 200
total = total + int(num)
print("The number of lines is : ", lines)
print ("The total sum is : " , total)
print("The average is :" , average)

Write list to 2 different text files

Reading in the data text file,
Running loops to check criteria for valid and invalid student numbers.
Then trying to write 2 text files, one for the invalid student numbers and one for the valid student numbers
This far everything works accept no text files written and no data written to text files at the end
Here is the Script so far
inputList = []
outputList = []
def FileOpen(myList):
#try:
count=0
INFILE=open("data.txt", "r")
for line in INFILE:
myList.append(line.rstrip())
count+=1
INFILE.close()
return count
#except:
# print("File could not be found")
# exit()
FileOpen(inputList)
print(FileOpen(inputList),"number of lines read from file")
def AnalyseStudents(rawStudents,totalStudents):
for entry in rawStudents:
amountOfDigits = len(entry)
testOfDigits = entry.isdigit()
def inValid1(val1,val2):
answ = val1 != 8 and val2 != True
return answ
inValidResult1=(inValid1(amountOfDigits,testOfDigits))
def Valid1(val1,val2):
answ = val1 == 8 and val2 == True
return answ
validResult1=(Valid1(amountOfDigits,testOfDigits))
if inValidResult1:
print(entry, " is an INVALID student number")
elif validResult1:
a=entry[0]
b=entry[1]
c=entry[2]
d=entry[3]
e=entry[4]
f=entry[5]
g=entry[6]
h=entry[7]
sum = float((a*8)+(b*7)+(c*6)+(d*5)+(e*4)+(f*3)+(g*2)+(h*1))
result = sum%11
def inValid2 (val):
answ = val != 0
return answ
inValidResult2=(inValid2(result))
def Valid2 (val):
answ = val == 0
return answ
validResult2=(Valid2(result))
if validResult2:
print(entry, " is an VALID student number")
elif inValidResult2:
print(entry, " is an INVALID student number")
totalStudents
AnalyseStudents(inputList,outputList)
def Write(outList):
if outList == (" is an VALID student number"):
OUTFILE1=open("ValidNumbers.txt","w")
for validResult in outList:
OUTFILE1.write(validResult+"\n")
OUTFILE1.close()
elif outList == (" is an INVALID student number"):
OUTFILE2=open("InvalidNumbers.txt","w")
for inValidResults in outList:
OUTFILE2.write(inValidResults+"\n")
OUTFILE2.close()
Write(outputList)
print("See output files for more details")
Your equality statements are wrong
if outList == (" is an VALID student number"):
...
elif outList == (" is an INVALID student number"):
The outList is a list but you are comparing it to strings. Put a debug breakpoint at those if statements and decide what you want.
I'm still working my way through this, but for the first function, you can use list comprehension and a couple of other Python functions. Commentary is included.
inputList = []
outputList = []
# Change parameter to the name of the file you want to open.
# Here, we can just make the parameter optional and pass your
# text file name by default.
def FileOpen(filename="data.txt"):
# Using with keeps the open file in context until it's finished
# it will then close automatically.
with open(filename, "r") as INFILE:
# Reach all the data at once and then try to decode it.
data = INFILE.read()
try:
data = data.decode("utf-8")
# If data can't be decoded, then it doesn't have that attribute.
# Catch that exception
except AttributeError:
pass
# Python 3 has a string method called .splitlines() that makes
# splitting lines a little simpler.
myList = [line for line in data.splitlines()]
# We'll return two values: The length (or count) of the list
# and the actual list.
return len(myList), myList
# We set up two variables for intake of our count and list results.
count, myList = FileOpen()
print("{} number of lines read from file".format(count))
EDIT: I don't know what the last part of your code is aiming to do. Maybe compare student count to valid entries? Here's the middle part. I moved the function outside and made it evaluate either valid or invalid in one fell swoop.
def is_valid(entry_value):
"""Validate current entry."""
if len(entry_value) != 8 and entry_value.isnumeric():
return False
return True
def AnalyseStudents(rawStudents, totalStudents):
for entry in rawStudents:
# Our new function will return True if the entry is valid
# So we can rework our function to run through the True condition
# first.
if is_valid(entry):
entry_sum = entry[0] * 8
entry_sum += entry[1] * 7
entry_sum += entry[2] * 6
entry_sum += entry[3] * 5
entry_sum += entry[4] * 4
entry_sum += entry[5] * 3
entry_sum += entry[6] * 2
entry_sum += entry[7] * 1
if entry_sum % 11 == 0:
print(entry, " is an VALID student number")
else:
print(entry, " is an INVALID student number")
else:
print(entry, " is an INVALID student number")
AnalyseStudents(inputList, outputList)

How can i speed up this python code?

So I recently coded this as a little challenge to see how quick I could do it. Now since its working an such I want to speed it up. It finds all the proper devisors of a number, the highest proper devisor and times how long it all takes. The problem is with number like 5000 it takes 0.05 secs but with numbers like 99999999999 it takes 1567.98 secs.
this the old code I have made a new and improved version below
import time
def clearfile(name):
file = open(name + ".txt", "r")
filedata = file.read()
file.close()
text_file = open(name + ".txt", "w")
text_file.write("")
text_file.close()
def start():
num = input("Enter your Number: ")
check(num)
def check(num):
try:
intnum = int(num)
except ValueError:
error(error = "NON VALID NUMBER")
if(intnum < 0):
error(error = "POSITIVE NUMBERS ONLY")
else:
finddivisor(intnum)
def finddivisor(intnum):
starttimer = time.time()
i = 1
print("\nThe divisors of your number are:"),
while i <= intnum:
if (intnum % i) == 0:
print(i)
file = open("numbers.txt", "r")
filedata = file.read()
file.close()
text_file = open("numbers.txt", "w")
text_file.write(str(i) +"\n"+ filedata)
text_file.close()
i += 1
properdivisor(starttimer)
def properdivisor(starttimer):
file = open("numbers.txt", "r")
highest = file.readlines()
print("\nThe Highest Proper Divisor Is\n--------\n" + highest[1] + "--------" + "\nIt took" ,round(time.time() - starttimer, 2) ,"seconds to finish finding the divisors.\n")
restart(errorrestart = "false")
def restart(errorrestart):
if errorrestart == "false":
input("Do You Want Restart?\nPress Enter To Restart Or Close The Programe To Leave")
start()
elif errorrestart == "true":
input("\nThere Was An Error Detected.\nPress Enter To Restart Or Close The Programe To Leave")
start()
def error(error):
print("\n----------------------------------\nERROR - " + error + "\n----------------------------------")
restart(errorrestart = "true")
clearfile(name = "numbers")
start()
Can someone speed it up for me
EDIT 1
so after looking over it I have now edited it to be moving it away from a file to an array
import time
from array import *
def programme():
num = input("Enter your Number: ")
try:
intnum = int(num)
except ValueError:
error("NOT VALID NUMBER")
if(intnum < 0):
error("POSITIVE NUMBERS ONLY")
else:
numbers = array("i",[])
starttimer = time.time()
i = 1
print("\nThe divisors of your number are:"),
while i <= intnum:
if (intnum % i) == 0:
numbers.insert(0,i)
print(i)
i += 1
print("\nThe Highest Proper Divisor Is\n--------\n" + str(numbers[1]) + "\n--------" + "\n\nIt took" ,round(time.time() - starttimer, 2) ,"seconds to finish finding the divisors.\n")
def error(error):
print("\n----------------------------------\nERROR - " + error + "\n----------------------------------\n")
running = True
while(running == True):
programme()
print("----------------------------------")
restart = input("Do You Want Restart?")
restart = restart.lower()
if restart in ("yes", "y", "ok", "sure", ""):
print("Restarting\n----------------------------------")
else:
print("closing Down")
running = False
New Edit
import time, math
from array import *
def programme():
num = input("Enter your Number: ")
try:
intnum = int(num)
if(intnum < 0):
error("POSITIVE NUMBERS ONLY")
else:
numbers = array("i",[])
starttimer = time.time()
i = 1
print("\nThe divisors of your number are:"),
while i <= math.sqrt(intnum):
if (intnum % i) == 0:
numbers.insert(0,i)
numbers.insert(0,int(intnum/i))
print(i,":", int(intnum/i))
i += 1
numbers = sorted(numbers, reverse = True)
print("The Highest Proper Divisor Is\n--------\n",str(numbers[1]) , "\n--------\nIt took" ,round(time.time() - starttimer, 2) ,"seconds to finish finding the divisors." )
except ValueError:
error("NOT VALID NUMBER")
except OverflowError:
error("NUMBER IS TO LARGE")
except:
error("UNKNOWN ERROR")
def error(error):
print("\n----------------------------------\nERROR - " + error + "\n----------------------------------\n")
running = True
while(running):
programme()
print("----------------------------------")
restart = input("Do You Want Restart?")
restart = restart.lower()
if restart in ("yes", "y", "ok", "sure", ""):
print("Restarting\n----------------------------------")
else:
print("closing Down")
running = False
If you have divisor a of number n then you can tell one more divisor of n b = n / a. Moreover if a <= sqrt(n) then b >= sqrt(n) and vice versa. It means in your finddivisor function you can iterate while i * i <= n and print both divisors i and n / i.
By the way, you shouldn't open, read and close files in cycle. Open it once before cycle and close after if you need to read/write several times.
You don't need to read and rewrite the entire file every time you want to put a single entry into it. You can just do it once when you know what change you want. Also you could just append to it. Maybe something like this:
def finddivisor(intnum):
starttimer = time.time()
print("\nThe divisors of your number are:")
divs = set()
for i in range(1, int(math.sqrt(intnum)) +1):
if intnum % i == 0:
print(i)
divs.add(i)
divs.add(intnum // i)
with open("numbers.txt", "a") as file:
file.writelines("{}\n".format(ln) for ln in sorted(divs, reverse=True))
also your program flow is building a very deep stack. Try and flatten it with something like
def start():
clearfile()
while True:
n = get_number()
starttimer = time.time()
finddivisor(n)
properdivisor(starttimer)
input("Press Enter To Restart Or Close The Programe To Leave")
in properdivisor you dont need to read the whole file either, you just need the first line. so maybe something like:
def properdivisor(starttimer):
with open(FILENAME, "r") as file:
highest = file.readline().strip()
print "\nThe Highest Proper Divisor Is"
print "--------%s--------" % highest
print "It took %0.2f seconds to finish finding the divisors.\n" % (time.time() - starttimer)
AFTER EDIT
Something like this is how I would do it, and it runs less then a second on my box:
import math
def get_divisors(n):
yield 1
sqroot = int(math.sqrt(n))
for x in xrange(2, sqroot):
if n % x == 0:
yield x
yield n / x
if sqroot**2 == n:
yield sqroot
divisors = sorted(get_divisors(999999999999))
print divisors

Unordered type error: int stored as string

I'm looping through a file to find the highest value and then return the value and number of lines. If I didn't convert myMax with int() I would get an unordered type error with the variable set as a string. What did I forget?!
def main():
myMax= 0
myCount = 0
myFile = open("numbers.dat", 'r')
for line in myFile :
myCount = myCount + 1
if int(line) > int(myMax):
myMax = line
myFile.close()
print ("Out of %s lines, the highest value found was %s" %(myCount, myMax))
main()
You need to change myMax = line to myMax = int(line). This will also make if int(line) > int(myMax): convertable to if int(line) > myMax:
This your file contains valid numbers and not strings that can't be converted to numbers.
with open('numbers.dat') as f:
lines = [int(line) for line in f if line.strip()]
print 'Out of %s lines, the highest value is %s' % (len(lines),max(lines))
I guess that the line 'myMax = line' cause it - you made type conversion(if int(line) > int(myMax):) but not assigned it. Wht if:
def main():
myMax = 0
with open("numbers.dat", 'r') as myFile:
for i, line in enumerate((int(x) for x in myFile)):
if line > myMax:
myMax = line
print ("Out of %s lines, the highest value found was %s" % (i, myMax))
main()
In a case you have empty lines and want to skip them:
def main():
myMax = 0
with open("numbers.dat", 'r') as myFile:
for i, line in enumerate((int(x) for x in myFile if x)):
if line > myMax:
myMax = line
print ("Out of %s lines, the highest value found was %s" % (i, myMax))
main()
This is what I used to solve your problem if your "numbers.dat" file has strings and numbers throughout the file. I had to break down the lines character by character and then build up any numbers that were of multiple digits into a string variable myTemp, then whenever there is not character that is a number I checked the size of myTemp and if there was anything in it make it into an integer and assign it to myInt, reset the myTemp variable back to empty (so if there is another number on the line it won't add to the number already there), and then compare it to the current Max. It's a couple ifs but I think it does the job.
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
def main():
myMax= 0
myCount = 0
myTemp = ''
lastCharNum = False
myFile = open("numbers.dat", 'r')
for line in myFile :
myCount = myCount + 1
for char in line: #go through each character on the line
if is_number(char) == False: #if the character isnt a number
if len(myTemp) == 0: #if the myTemp is empty
lastCharNum = False #set lastchar false
continue #then continue to the next char
else: #else myTemp has something in it
myInt = int(myTemp)#turn into int
myTemp = '' #Flush myTemp variable for next number (so it can check on same line)
if myInt > myMax: #compare
myMax = myInt
else:# otherwise the char is a num and we save it to myTemp
if lastCharNum:
myTemp = myTemp + char
lastCharNum = True #sets it true for the next time around
else:
myTemp = char
lastCharNum = True #sets it true for the next time around
myFile.close()
print ("Out of %s lines, the highest value found was %s" %(myCount, myMax))
main()
If the "numbers.dat" file has only numbers on each line then this solves it pretty easy:
def main():
myMax= 0
myCount = 0
myFile = open("numbers.dat", 'r')
for line in myFile :
myCount = myCount + 1
if int(line) > myMax: #compare
myMax = int(line)
myFile.close()
print ("Out of %s lines, the highest value found was %s" %(myCount, myMax))
main()

Categories