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)
Related
I came across a project geared toward starters like myself - creating a CLI passwordcreator.
I have with the help of a few guides completed the generator and added a few of my own features, however there is one feature I can't seem to figure out how to implement; saving the output to a file.
In the terminal the passwords shows up perfectly fine line by line, however if I try to save the output to a file it only saves the last password, and it seperates each letter by line.
My code is below, together with examples of output from both the terminal and a .txt file.
import string
import random
from os import system, name
letters = list(string.ascii_letters)
digits = list(string.digits)
special_characters = list("!##$%^&*()£")
characters = list(string.ascii_letters + string.digits + '!##$%^&*()£')
def clear():
if name == 'nt':
_ = system('CLS')
else:
_ = system('clear')
def generate_random_password():
clear()
length = int(input("Enter password length: "))
amount = int(input('Enter amount of passwords: '))
letters_count = int(input("Enter letter count: "))
digits_count = int(input("Enter digits count: "))
special_characters_count = int(input("Enter special characters count: "))
character_count = letters_count + digits_count + special_characters_count
if character_count > length -1:
print("Characters total count is greater than desired password length")
exit()
clear()
password = []
print("Following passwords saved to Passwords.txt, please move the file before generating new passords, as a new generation will overwrite existing")
print('\n')
for pwd in range(amount):
password = []
for c in range(digits_count):
password.append(random.choice(digits))
for c in range(letters_count):
password.append(random.choice(letters))
for c in range(special_characters_count):
password.append(random.choice(special_characters))
if character_count < length:
random.shuffle(characters)
for c in range(length - character_count):
password.append(random.choice(characters))
random.shuffle(password)
if str(password) < str(length):
return()
else:
print("".join(password))
with open('Passowrds.txt', 'w') as file:
for line in ("".join(password)):
file.write(line)
file.write('\n')
#file = open('Passwords.txt', 'w')
#str1 = repr(password)
#file.write('\n' + str1 + '\n')
#file.close
#f = open('Passwords.txt', 'r')
#if f .mode == 'r':
# contents=f.read
generate_random_password()
This is what the output from the terminal looks like:
Following passwords saved to Passwords.txt, please move the file
before generating new passords, as a new generation will overwrite
existing
gtBVA3QDcUohDc£TfX(zVt*24
KD8PnMD£)25hvHh#3xj79$qZI
Dx^*2£srcLvRx5g3B3(nq0H&9
&r6^3MEsaV1RuDHzxq*(h3nO)
However what is saved in the .txt file looks like this:
&
r
6
^
3
M
E
s
a
V
1
R
u
D
H
z
x
q
*
(
h
3
n
O
)
The reason why your script is saving only 1 password is because you are opening the file to be written (which clears the contents of the file) for every password you are generating.
You want to do something along the lines of:
passwords = []
for _ in range(num_passwords):
password = ...
passwords.append(password)
with open("password.txt", "w") as f:
f.writelines(passwords)
Although there is nothing terrible about the way you're using the random library, I recommend taking a look at random.sample (without replacement) or random.choices (with replacement).
Also, using shuffling your characters list isn't adding additional randomness to your random.choice.
You don't have to convert the strings to lists in order to run choice:
>>> import random
>>> random.choice("abc")
'b'
A fuller example:
def generate_random_password():
clear()
length = int(input("Enter password length: "))
amount = int(input("Enter amount of passwords: "))
letters_count = int(input("Enter letter count: "))
digits_count = int(input("Enter digits count: "))
special_characters_count = int(input("Enter special characters count: "))
character_count = letters_count + digits_count + special_characters_count
if character_count > length - 1:
print("Characters total count is greater than desired password length")
exit()
clear()
passwords = []
for _ in range(amount):
chosen_digits = random.choices(digits, k=digits_count)
chosen_letters = random.choices(letters, k=letters_count)
chosen_special_characters = random.choices(
special_characters, k=special_characters_count
)
extra_characters_count = length - character_count
extra_characters = random.choices(characters, k=extra_characters_count)
password = (
chosen_digits
+ chosen_letters
+ chosen_special_characters
+ extra_characters
)
random.shuffle(password)
passwords.append("".join(password))
with open("Passwords.txt", "w") as f:
f.writelines(passwords)
I fixed most of my code but the only problem I'm having is that none of the text is showing. I'm supposed to input golfer names and their scores but nothing shows up when I run the program.
def main():
inGolf = open('golfers.txt', 'r')
names = []
scores = []
for line in inGolf:
line_list = line.split(",")
names.append(line_list[0])
scores.append(line_list[1])
for i in range(len(names)):
print ("{0:20}{1:10}".format(names[i], scores[i]))
inGolf.close()
def w(numPlayers):
counter = 0
outGolf = open('playerData.txt', 'w')
while counter < numPlayers:
name = raw_input("Please enter the player's name:")
outGolf.write(name + ",")
score = input("Please enter that player's score:")
outGolf.write(str(score) + "\n")
counter = counter + 1
outGolf.close()
main()
I have slightly modified this script to try it here and it actually worked:
It prompts the players' names and scores by players number.
It saves the players file
It reads the players file and show scoring results.
I had to change raw_input to input as for Python3 and called the w function passing a number of player by user inputs:
def main():
num_players = input("How many players?")
w( int(num_players) )
inGolf = open('golfers.txt', 'r')
names = []
scores = []
for line in inGolf:
line_list = line.split(",")
names.append(line_list[0])
scores.append(line_list[1])
for i in range(len(names)):
print ("{0:20}{1:10}".format(names[i], scores[i]))
inGolf.close()
def w(numPlayers):
counter = 0
outGolf = open('golfers.txt', 'w')
while counter < numPlayers:
name = input("Please enter the player's name:")
outGolf.write(name + ",")
score = input("Please enter that player's score:")
outGolf.write(str(score) + "\n")
counter = counter + 1
outGolf.close()
main()
def open_file():
data=open("data_full.txt")
return data
def process_file(data):
out_file = input("Enter a name for the output file: ")
output_file= open(out_file, "w")
user_year = int(input("Enter a year: "))
user_int_count= int(input("Enter a integer count: "))
cnt = 0
data.readline()
for line in data:
cnt+= 1
field = line.strip().split()
line_list = [int(n) for n in field]
total = sum(line_list[1:])
year = line_list[0]
avg = int(round((total/12),0))
if user_year == year:
output_file.write("{:<d} {:<d}".format(year, avg))
print()
print( "{:<d} {:<d}".format(year, avg))
output_file.close()
def main():
while True:
try:
f=open_file()
break
except FileNotFoundError:
print("Invalid file name. Try Again.")
process_file(f)
f.close()
main()
this should print a range from the year entered through the incremented value assuming that's what your asking. If not please rephrase your question as it is a bit hard to interpret.
for x in range(user_year, user_year + count):
print x
I'm basing this answer on a more literal interpretation of the question.
def year_range(year_date, number_of_years): #assuming these are of type int.
output = '{}-{}'.format(year_date, year_date+number_of_years)
print(output)
so year_range(2000, 5)
gives you "2000-2005"
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
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)))