Timing this programs duration while it runs - python

Here's the entire program, but I'm trying to figure out how to time it (days:hours:minutes:seconds) if at all possible. It is written in Python.
import random
x = 1
attempt = 0
while x ==1:
rand1 = random.randint(1,1000)
rand2 = random.randint(1,1000)
attempt = attempt + 1
if rand1 ==rand2:
x=2
print(rand1)
print(rand2)
print("Match Found.")
else:
print(rand1)
print(rand2)
print("Trying again.")
print("")
print("It took ", attempt," attempts to find a matching number.")
#for x in range(10):
# rand1 = random.randint(1,101)
# print(rand1)
# ignore the googol that's what I'm using when I figure out how to time it -> 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

The better code:
import random
import time
from datetime import datetime
from datetime import timedelta
print('Current time: %s' % datetime. now())
attempt = 0
start_time = time.time()
while 1:
rand1 = random.randint(1,1000)
rand2 = random.randint(1,1000)
attempt += 1
if rand1 == rand2:
print(rand1)
print(rand2)
print("Match Found.", end = '\n\n')
break
else:
print(rand1)
print(rand2)
print("Trying again.", end = '\n\n')
print("It took %s attempts to find a matching number." % attempt)
print("It took %s to finish" % str(timedelta(seconds=(time.time() - start_time))))

Related

Python Change variable inside a loop while looping through it

I just startet with Python and wanted to make a little countdown app, i am able to do it with seconds but when i try to do it with minutes it just goes into the negatives, i tried it with a if statement but instead it goes into the negatives. Any Ideas? Also anything I should change to make my code cleaner? Thanks in advance :)
import winsound
frequency = 1000
duration = 1000
def calc(num):
if dictionary["unit"] == "seconds":
for i in range(num):
print(num)
time.sleep(1)
num = num - 1
if num == 0:
winsound.Beep(frequency, duration)
elif dictionary["unit"] == "minutes":
num2 = 60
sum = 60
for i in range(num*60):
num2 = num2 -1
print(f"{num} Minutes {num2}")
time.sleep(0.005)
if num2 == 0:
num -1
num2 +60
def validation():
try:
number = int(dictionary["time"])
if number > 0:
calc(number)
except ValueError:
print("Do it again")
user = (input("Enter your Time\n"))
splitet = user.split()
dictionary = {"time": splitet[0], "unit": splitet[1]}
validation()
You can convert the minutes to seconds and do while loop for counting down. in for range loop, i already acts like a count down so you don't need to check if num is 0.
import time
import winsound
frequency = 1000
duration = 1000
def parse_time(input_str):
parts = input_str.split()
if len(parts) != 2:
raise ValueError("Wrong format.")
try:
number = int(parts[0])
except ValueError:
raise ValueError("Time is not integer")
if number <= 0:
raise ValueError("Negative Time")
return number, parts[1]
def calculate_seconds(count, measure):
if measure == "seconds":
return count
if measure == "minutes":
return 60 * count
def countdown(n_sec):
# A reversed range loop to count down
# i will decrease from n_sec to 0 in each iteration
for i in reversed(range(n_sec)):
print("%d minutes %d seconds" % (i / 60, i %60))
time.sleep(1)
winsound.Beep(frequency, duration)
if __name__ == "__main__":
# Use raw_input for raw string input.
input_str = raw_input("Enter your Time\n")
count, measure = parse_time(input_str)
seconds = calculate_seconds(count, measure)
countdown(seconds)

My loop is running endlessly even though i have an end condition after i run the code

im doing a small "mastermind" game for a project, seems to run fine up until my last while loop, i thought i have an end statement but it seems to run on repeat. I've been stuck on this for some time now and i would appreciate any and all help on this, thanks! Here is the code:
import random
def generate_code():
"""Create a random code as a list"""
for i in range(0,4):
i = random.randint(0,5)
code.append(i)
print(code)
def make_guess():
"""Let's the user input a guess"""
while len(guess) < 4:
element = input("your guess, one at the time: " )
if element.isnumeric():
element = int(element)
global amountOfGuesses
if element in range(0,6):
guess.append(element)
amountOfGuesses = amountOfGuesses +1
else:
print("number has to be between 0 and 5")
else:
print("has to be a number between 0 and 5")
def right_position(guess, code):
"""Calculate how many correkt numbers on right position the guess have"""
howManyRight = 0
for i in range(4):
if guess[i] == code[i]:
howManyRight = howManyRight +1
return howManyRight
def wrong_position(guess, code):
"""Calculate how many numbers are corret but wrong position"""
howManyWrongPosition = 0
tempCode = code[:]
for i in guess:
if i in tempCode:
tempCode.remove(i)
howManyWrongPosition = howManyWrongPosition +1
howManyWrongPosition = howManyWrongPosition - right_position(guess, code)
return howManyWrongPosition
code = []
guess = []
wrongPosition = []
rightPosition = []
codeCopy = code.copy()
amountOfGuesses = 0
print("Welcome to Mastermind.\nYou get seven guesses to gues a random 4 digit code with 6 different numbers between 0 and 5.")
generate_code()
while amountOfGuesses <= 7:
make_guess()
print("you have", right_position(guess, code), "right numbers on the right position")
print("you have", wrong_position(guess, code), "numbers on that is right but on the wrong posiotion")
if guess[:] == code[:]:
print("Congratulation you won!!! you used", amountOfGuesses, "guesses.")
From what I understand you want one try to be one input of 4 numbers, so I also fixed that. The reason you're getting an infinite loop is because you haven't broken out of the loop at end. You should also clear the guess array, otherwise the for loop inside the make_guess() will just skip due to the length being 4 (in case the guess was wrong and want to try again).
The fixed code (assuming one try is input of 4 numbers):
import random
def generate_code():
"""Create a random code as a list"""
for i in range(0,4):
i = random.randint(0,5)
code.append(i)
print(code)
def make_guess():
"""Let's the user input a guess"""
global amountOfGuesses
while len(guess) < 4:
element = input("your guess, one at the time: " )
if element.isnumeric():
element = int(element)
if element in range(0,6):
guess.append(element)
else:
print("number has to be between 0 and 5")
else:
print("has to be a number between 0 and 5")
amountOfGuesses = amountOfGuesses +1
def right_position(guess, code):
"""Calculate how many correkt numbers on right position the guess have"""
howManyRight = 0
for i in range(4):
if guess[i] == code[i]:
howManyRight = howManyRight +1
return howManyRight
def wrong_position(guess, code):
"""Calculate how many numbers are corret but wrong position"""
howManyWrongPosition = 0
tempCode = code[:]
for i in guess:
if i in tempCode:
tempCode.remove(i)
howManyWrongPosition = howManyWrongPosition +1
howManyWrongPosition = howManyWrongPosition - right_position(guess, code)
return howManyWrongPosition
code = []
guess = []
wrongPosition = []
rightPosition = []
codeCopy = code.copy()
amountOfGuesses = 0
print("Welcome to Mastermind.\nYou get seven guesses to gues a random 4 digit code with 6 different numbers between 0 and 5.")
generate_code()
while 1:
make_guess()
print("you have", right_position(guess, code), "right numbers on the right position")
print("you have", wrong_position(guess, code), "numbers on that is right but on the wrong posiotion")
if guess == code:
print("Congratulation you won!!! you used", amountOfGuesses, "guesses." if amountOfGuesses > 1 else "guess.")
break
elif amountOfGuesses > 7:
print(f"You have lost by using {amountOfGuesses} tries!")
break
guess = []

I've write a code and I'm getting error while using matplotlib in the editor I am getting invalid syntax error, does anyone know why?

import matplotlib.pyplot as plt
import time as t
times = []
mistake = 0
print("you will have to type the word 'programming' as fast as you can for five times")
input("Press Enter to Continue.")
while len(times) < 5
start = t.time()
word = input("Type the Word: ")
end = t.time()
time_elapsed = end - start
times.append(time_elapsed)
if(word.lower()! = "programming"):
mistake += 1
print("You made" + str(mistake) + "mistakes.")
print("Now let's See your evolution")
t.sleep(3)
x = [1,2,3,4,5]
y = times
plt.plot(x,y)
legend = ["1","2","3","4","5"]
plt.xticks(x,legend)
plt.ylabel("Time in Seconds")
plt.xlabel("Attempts")
plt.title("Your Typing Evolution")
plt.show()
The only problem was with the indentation and syntax. After these errors removed, your code is working fine. The code without any errors is:
import matplotlib.pyplot as plt
import time as t
times = []
mistake = 0
print("you will have to type the word 'programming' as fast as you can for five times")
input("Press Enter to Continue.")
while len(times) < 5:
start = t.time()
word = input("Type the Word: ")
end = t.time()
time_elapsed = end - start
times.append(time_elapsed)
if word.lower() != "programming":
mistake += 1
print("You made" + str(mistake) + "mistakes.")
print("Now let's See your evolution")
t.sleep(3)
x = [1,2,3,4,5]
y = times
plt.plot(x,y)
legend = ["1","2","3","4","5"]
plt.xticks(x,legend)
plt.ylabel("Time in Seconds")
plt.xlabel("Attempts")
plt.title("Your Typing Evolution")
plt.show()

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

Python number increment

I am experimenting with python, and I've made this little math game. Though I am having some issue with a scoring system. Each time the player gets an answer correct, I want the score to increment by 1. I have tried, however I haven't got it to increase each time the player gets something right.
Heres the code
import operator
import random
operations = {
"addition": ("+", operator.add),
"substraction": ("-", operator.sub),
"multiplication": ("*", operator.mul),
"division": ("/", operator.floordiv),
}
def ask_operation(difficulty, maxtries=3):
maxvalue = 5 * difficulty
x = random.randint(1, maxvalue)
y = random.randint(1, maxvalue)
op_name, (op_symbol, op_fun) = random.choice(list(operations.items()))
result = op_fun(x, y)
score = 0
print("Difficulty level %d" % difficulty)
print("Now lets do a %s calculation and see how clever you are." % op_name)
print("So what is %d %s %d?" % (x, op_symbol, y))
for ntry in range(1, 1+maxtries):
answer = int(input(">"))
if answer == result:
print("Correct!")
score += 1
print score
return True
elif ntry == maxtries:
print("That's %s incorrect answers. The end." % maxtries)
else:
print("That's not right. Try again.")
return False
def play(difficulty):
while ask_operation(difficulty):
difficulty += 1
print("Difficulty level achieved: %d" % difficulty)
play(1)
The score is reset to 0 every time in ask_operation. You should initialize it in play instead.
By the way, //Increment score// is not valid Python. You can set comments in Python like this, even in Stack Overflow.
score += 1 # Increment score

Categories