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
Related
def myNames():
names = []
while True:
a = input("Enter Name: ")
if a != "done":
names.append(a)
elif a == "done":
return names
def all_lengths(myNames):
num_of_strings = len(myNames)
total_size = 0
for item in myNames:
total_size += len(item)
ave_size = float(total_size) / float(num_of_strings)
print(ave_size)
all_lengths(myNames())
def longestWord(myNames):
count = 0
for i in myNames:
if len(i) > count:
count = len(i)
word = I
print ("the longest string is ", word)
how can I make it print the longest name that was inputted by the user for example: out of Samantha and John it would say that Samantha was the longest name
longestName = ""
for name in myNames:
if len(name) > len(longestName):
longestName = name
print("The longest name is", longestName)
This will check the length of each username, and if the name of that username is longer than the current longest username, it will replace it.
You already have the function for it.
Just need to call the function longestWord().
Write longestWord(myNames()) at the end of the program. Right after,
def longestWord(myNames):
count = 0
for i in myNames:
if len(i) > count:
count = len(i)
word = i # Need to type I in lower case
print ("the longest string is ", word)
Update: Since, you don't want the function to ask for names again, you can move the function calling longestWord()inside the above function where it calculates average, with the parameter as myNames i.e.
def myNames():
names = []
while True:
a = input("Enter Name: ")
if a != "done":
names.append(a)
elif a == "done":
return names
def longestWord(myNames):
count = 0
for i in myNames:
if len(i) > count:
count = len(i)
word = i
print ("the longest string is ", word)
def all_lengths(myNames):
num_of_strings = len(myNames)
total_size = 0
for item in myNames:
total_size += len(item)
ave_size = float(total_size) / float(num_of_strings)
print(ave_size)
longestWord(myNames) # Calling the function with already given names
all_lengths(myNames())
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)
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)
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
while True:
try:
file = input("Enter a filename: ")
fi = open(file, "r")
infile = fi.read()
grid = [list (i) for i in infile.split()] #Puts the sudoku puzzle into a list in order to check that the total number is valid
check = len(grid)
print("The total number in this puzzle is:",check) #Counts the amount of numbers in the sudoku puzzle
break
except FileNotFoundError:
print ("The inputted file does not exist")
def check(infile):
count = 0
for j in range (0,9):
for n in range(0,9):
if infile[j].count(infile[j][n]) <= 1:
count = count + 0
else:
count = count + 1
cols = [[row[i] for row in infile] for i in[0,1,2,3,4,5,6,7,8]]
leg = 0
for i in range(0,9):
for j in range(0,9):
if cols[i].count(cols[i][j]) <= 1:
leg = leg + 0
else:
leg = leg + 1
angel = []
for t in range(3):
ang = infile[t]
for u in range(3):
angel.append(ang[u])
foot = 0
for be in range(9):
if angel.count(angel[be]) <= 1:
foot = foot + 0
else:
foot = foot + 1
if count + leg + foot == 0:
print("Valid")
else:
print ("Invalid")
def inputs():
x = raw_input()
ls = []
while x != '':
x1 =x.split(' ')
ls.append(x1)
if len(infile) >=9:
print (check(infile))
infile = []
x = raw_input()
inputs()
actual error:
Traceback (most recent call last):
File "E:/Computer Programming/Assignment/check 2.py", line 22, in <module>
cols = [[row[i] for row in infile] for i in[0,1,2,3,4,5,6,7,8]]
File "E:/Computer Programming/Assignment/check 2.py", line 22, in <listcomp>
cols = [[row[i] for row in infile] for i in[0,1,2,3,4,5,6,7,8]]
File "E:/Computer Programming/Assignment/check 2.py", line 22, in <listcomp>
cols = [[row[i] for row in infile] for i in[0,1,2,3,4,5,6,7,8]]
IndexError: string index out of range
Why does it give an output to say that my string index is out of range, is there another way to create a sudoku 9x9 checker to check if there are any reoccurring numbers. I need to make sure that there are 9 numbers in each column and that they are between the numbers 1 and 9
first, a few comments:
never do:
cols = [[row[i] for row in infile] for i in[0,1,2,3,4,5,6,7,8]]
but do:
cols = [[row[i] for row in infile] for i in range(0,9)]
never call a variable the same name as a function you've defined in your code check and check()
don't write code at the module level, but embed everything in functions, and call the entry point function at the end of the file after the if __name__ == "__main__" condition (so in case you want to import your module in another module, you don't execute module level code).
don't open files without closing them, instead use the context manager: with open('myfile', 'r') as f: ...
your code features an useless use of while... or at least a wrong use (do you really mean to loop forever on an exception?) use command line arguments instead, that will make the shell help your user choose a file that does actually exists.
now I've made all that clear, here's about your actual question:
infile is a file object (if I can read correctly your mis-indented python code), thus every line - called row here - of infile is just a string.
So if you have an empty line or a line that is less than 9 columns, you're likely to get row[i] out of boundaries.
here's a take at refactoring your code, though I've left a number of wrong design over:
def check(infile):
count = 0
for j in range (0,9):
for n in range(0,9):
if infile[j].count(infile[j][n]) <= 1:
count = count + 0
else:
count = count + 1
def inputs():
x = raw_input()
ls = []
while x != '':
x1 =x.split(' ')
ls.append(x1)
if len(infile) >=9:
print (check(infile))
infile = []
x = raw_input()
def check_grid():
cols = [[row[i] for row in infile] for i in range(0,9)]
leg = 0
for i in range(0,9):
for j in range(0,9):
if cols[i].count(cols[i][j]) <= 1:
leg = leg + 0
else:
leg = leg + 1
angel = []
for t in range(3):
ang = infile[t]
for u in range(3):
angel.append(ang[u])
foot = 0
for be in range(9):
if angel.count(angel[be]) <= 1:
foot = foot + 0
else:
foot = foot + 1
if count + leg + foot == 0:
print("Valid")
else:
print ("Invalid")
inputs()
def sudoku_checker():
try:
file = input("Enter a filename: ")
fi = open(file, "r")
infile = fi.read()
grid = [list (i) for i in infile.split()] #Puts the sudoku puzzle into a list in order to check that the total number is valid
# Counts the amount of numbers in the sudoku puzzle
print("The total number in this puzzle is:",len(grid))
check_grid()
except FileNotFoundError:
print ("The inputted file does not exist")
if __name__ == "__main__":
sudoku_checker()