Implementing a match counter into a lotto number guesser - python

im rather new to python and found someones lottery simulation in github. After playing around with it for a while i wanted to add a counter, that counts the number of matches of your Number out of the total draws.
I don't know if it is because i did not write the code myself, but i can't seem to make it happen. I've tried some of pythons counter modules bu that did'nt seem to be the right thing.
Heres my code:
import random
import time
### TODO - Refactor GetDrawNumbers (add timers)
### TODO - Refactor CheckNumbers
def GetDrawNumbers():
drawNumbers = []
for i in range(6):
x = None
while (x == None or x in drawNumbers):
x = random.randint(1, 49)
drawNumbers.append(x)
return drawNumbers
def CheckNumbers(myTicket, actualNumbers):
numbersMatched = 0
for number in myTicket:
if number in actualNumbers:
numbersMatched += 1
return numbersMatched
### Script starts here
startTime = time.perf_counter()
myNumbers = [4, 8, 15, 16, 23, 42]
for draw in range(2000):
drawNumber = draw + 1
thisWeeksDraw = GetDrawNumbers()
numbersMatched = CheckNumbers(myNumbers, thisWeeksDraw)
##print("Week " + str(drawNumber) + " numbers : " + str(thisWeeksDraw) + " (" + str(numbersMatched) + " matched)")
if numbersMatched == 4:
print("Week " + str(drawNumber) + " numbers : " + str(thisWeeksDraw) + " (" + str(numbersMatched) + " matched)")
count = numbersMatched
print("Total matches: " + str(count))
endTime = time.perf_counter()
elapsedTime = endTime - startTime
print("Completed in " + str(elapsedTime) + " seconds!")
If anyone knows a way to implement a counter, that counts the number of times this the program gets 3,4,5 or 6 correct matches i would be super relieved! It's not that this project would be super important but solving the problem would be a milestone for me and my learning process!
Thanks in advance and best wishes!

How about this where I have added a check of the numbersMatched value and increment a counter whenever it is 3 or more
import random
import time
### TODO - Refactor GetDrawNumbers (add timers)
### TODO - Refactor CheckNumbers
def GetDrawNumbers():
drawNumbers = []
for i in range(6):
x = None
while (x == None or x in drawNumbers):
x = random.randint(1, 49)
drawNumbers.append(x)
return drawNumbers
def CheckNumbers(myTicket, actualNumbers):
numbersMatched = 0
for number in myTicket:
if number in actualNumbers:
numbersMatched += 1
return numbersMatched
### Script starts here
startTime = time.perf_counter()
myNumbers = [4, 8, 15, 16, 23, 42]
countOfThreeOrMoreMatched = 0
for draw in range(2000):
drawNumber = draw + 1
thisWeeksDraw = GetDrawNumbers()
numbersMatched = CheckNumbers(myNumbers, thisWeeksDraw)
##print("Week " + str(drawNumber) + " numbers : " + str(thisWeeksDraw) + " (" + str(numbersMatched) + " matched)")
if numbersMatched >= 3:
countOfThreeOrMoreMatched += 1
if numbersMatched == 4:
print("Week " + str(drawNumber) + " numbers : " + str(thisWeeksDraw) + " (" + str(numbersMatched) + " matched)")
print(f"Count with 3 or more matches {countOfThreeOrMoreMatched}")
count = numbersMatched
print("Total matches: " + str(count))
endTime = time.perf_counter()
elapsedTime = endTime - startTime
print("Completed in " + str(elapsedTime) + " seconds!")

Related

How do I make random.randint refresh while program is running?

I'm making a small program that shoots out math problems and requires an answer to pass. It works fine, but all the randint values I generate stay static for as long as the progran is running. I figured if I change:
Tehtävä = random.choice(Laskut)
Into a function it should refresh with the loop. Problem is I can't for the life of me figure out how to do that. Would it even work for what I'm trying? The randint values are determined in a seperate list. Heres the rest of the code:
Peli = 1
while Peli != 2:
pulma = 1
refresh = 1
Tehtävä = random.choice(Laskut)
while pulma == 1:
ratkaisu = float(input(Tehtävä.problem + "\n:"))
if ratkaisu == Tehtävä.answer:
pulma += 1
refresh += 1
print("oikein")
elif ratkaisu == "loppu":
pulma += 1
refresh += 1
Peli += 1
else:
print("väärin")
Here are the values I used:
import random
class Algebra:
def __init__(self, problem, answer):
self.problem = problem
self.answer = answer
#Muuttujat
#erotus ja summa
a = random.randint(1,99)
b = random.randint(1,99)
c = random.randint(1,99)
d = random.randint(1,99)
#jako ja kerto
e = random.randint(1,10)
f = e*random.randint(1,10)
g = random.randint(1,10)
#Kysymykset
Kysymys_M = [str(a) + "+" + str(b) + "-x=" + str(c),
str(a) + "-" + str(b) + "-x=" + str(a),
str(a) + "-" + str(b) + "-" + str(c) + "-x=" + str(d),
str(e) + "*x=" + str(f),
str(f) + ":x=" + str(e),
"x:" + str(e) + "=" + str(g)]
#Vastaukset
Vastaus_M = [a+b-c,
-b,
a-b-c-d,
f/e,
f/e,
e*g]
Laskut = [
Algebra(Kysymys_M[0], Vastaus_M[0]),
Algebra(Kysymys_M[1], Vastaus_M[1]),
Algebra(Kysymys_M[2], Vastaus_M[2]),
Algebra(Kysymys_M[3], Vastaus_M[3]),
Algebra(Kysymys_M[4], Vastaus_M[4]),
Algebra(Kysymys_M[5], Vastaus_M[5]),]
(If I have packed too much information please let me know.)

Continue executing code without interrupting output of looping function

I have a while loop counting in centiseconds and printing the current_step var, always on the same line.
I want to run, for example,
x = True
while x is True:
pass #printing timer to CLI here
print('this is more code running while the timer is still running')
input('Press enter to stop the timer')
x = False
#When x becomes False, I want the while loop to terminate
I know this must involve subprocess or something of the likes, but I don't know what direction to point myself in for learning to solve this issue.
Here is the function for reference:
def timer(stawt, stahp, step, time_step):
from time import sleep
stawt = int(stawt)
stahp = int(stahp)
if stahp < 1:
stahp = 1
elif stahp > 1000:
stahp = 1000
stahp = stahp * 100 + 1
titerator = iter(range(stawt, stahp, step))
while True:
try:
current_step = str(next(titerator))
if int(current_step) < 99:
final_time = '0' + current_step[:0] + '.' + current_step[0:] + 's'
print('\r' + final_time, end='')
elif int(current_step) < 999:
final_time = current_step[:1] + '.' + current_step[1:] + 's'
print('\r' + final_time, end='')
elif int(current_step) < 9999:
final_time = current_step[:2] + '.' + current_step[2:] + 's'
print('\r' + final_time, end='')
else:
final_time = current_step[:3] + '.' + current_step[3:] + 's'
print('\r' + final_time, end='')
sleep(time_step)
except:
print(); break
seconds = int((int(current_step) / 100) % 60)
minutes = int((int(current_step) / 100) // 60)
if minutes < 1:
return ''
else:
final_time_human = str(minutes) + 'm ' + str(round(seconds)) + 's'
print(final_time_human + '\n')
def MAIN():
count_to = float(input('Enter max number of seconds to count:\n'))
print()
timer(0, count_to, 1, 0.01)
MAIN()
You need to use threading.
import threading
x = True
def thread_function():
while x is True:
pass #printing timer to CLI here
threading.Thread(target=thread_function).start()
# Continue with the other steps you want to take
# ...
# This will terminate the timer loop
x = False
Python threading documentation: https://docs.python.org/3/library/threading.html
If you want to print the time always at the same line you need to control terminal cursor. For more information checkout: How can move terminal cursor in Python?
Thanks to #dorukerenaktas, I have got this working. This is their answer adapted into my scriptlet:
import threading
from os import system
timer_thread = None
def timer(stawt, stahp, step, time_step):
from time import sleep
global run_timer
stawt = int(stawt)
stahp = int(stahp)
if stahp < 1:
print('Sorry, I limit min count to 1 second!\n')
stahp = 1
elif stahp > 1000:
print('Sorry, I limit max count to 1000 seconds!\n')
stahp = 1000
else:
print()
stahp = stahp * 100 + 1
titerator = iter(range(stawt, stahp, step))
def print_time():
while run_timer is True:
try:
current_step = str(next(titerator))
if int(current_step) < 99:
final_time = '0' + current_step[:0] + '.' + current_step[0:] + 's'
print('\r' + final_time, end='')
elif int(current_step) < 999:
final_time = current_step[:1] + '.' + current_step[1:] + 's'
print('\r' + final_time, end='')
elif int(current_step) < 9999:
final_time = current_step[:2] + '.' + current_step[2:] + 's'
print('\r' + final_time, end='')
else:
final_time = current_step[:3] + '.' + current_step[3:] + 's'
print('\r' + final_time, end='')
sleep(time_step)
except:
break
seconds = int((int(current_step) / 100) % 60)
minutes = int((int(current_step) / 100) // 60)
if minutes < 1:
return ''
else:
final_time_human = str(minutes) + 'm ' + str(round(seconds)) + 's'
print('\n' + final_time_human)
print_time()
def _init_timer():
global run_timer; run_timer = True
global timer_thread
print('Enter max number of seconds to count: ', end='')
count_to = float(input())
timer_thread = threading.Thread(target=timer, args=(0, count_to, 1, 0.01))
timer_thread.start()
print('\rPress enter to stop the timer:')
usr_input = input(); run_timer = False
system('clear')
_init_timer()
timer_thread.join()
print('\nGoodbye!')

Can anyone please advise me where I'm going wrong with this binary search code? Unable to print index to user

def binarySearch(list, selection):
start = 0
end = len(list) - 1
while start <= end:
middle = start + (end - start) // 2
middleValue = list[middle]
if middleValue == selection:
return middle
elif selection < middleValue:
end = middle - 1
else:
start = middle + 1
return None
lista = [1, 5, 7, 10, 11, 19,]
print(lista)
selectiona = int(input('Enter a number to search for: '))
index = lista.index(selectiona)
binarySearch(lista, selectiona)
print(str(selectiona)) + "found at index " + str(index))
exit = input()
It works without printing the index, but this is a requirement. If anyone can advise me on what I'm doing wrong I'd be greatly appreciative. thanks
In the line print(str(selectiona)) + "found at index " + str(index)) your parentheses are wrong, you close one too many after selectiona. Try this instead:
print(str(selectiona) + "found at index " + str(index))
Additionally, the result of your binary search isn't what you're printing. Did you mean to do index = binarySearch(lista, selectiona) instead?
You are fetching the index using python modules in the line index = lista.index(selectiona) and you are not using the output provides by the binarySearch function.
def binarySearch(list, selection):
start = 0
end = len(list) - 1
while start <= end:
middle = start + (end - start) / 2
middleValue = list[middle]
if middleValue == selection:
return middle
elif selection < middleValue:
end = middle - 1
else:
start = middle + 1
return None
lista = [1, 5, 7, 10, 11, 19,]
print(lista)
selectiona = int(input('Enter a number to search for: '))
index = binarySearch(lista, selectiona)
if index:
print(str(selectiona) + " found at index " + str(index))
else:
print(str(selectiona) + " is not there in the list")
exit = input()

Conditional statement printing values twice python

So I am testing my script in which i am passing two values to compare. It goes through two conditional statements. I have carried out some debugging and it prints out the same expression twice which is "Current value is in range". It first prints it out from the first loop and then from the second loop. I am not sure why my code is doing that. It should only print that out once and get out of the else statement and not go in to the second else statement which it is currently doing. What is that I am doing wrong to stop this.
def compare_sizes(previous_size, current_size):
subtract_f1_f2 = int(current_size - previous_size)
range_num = 0.4
range_previous_day = int(previous_size * range_num)
if subtract_f1_f2 > 0 and range_previous_day > 0 and subtract_f1_f2 >= range_previous_day:
whole_percent = subtract_f1_f2 / previous_size * 100
print (human_bytes(previous_size) +" -> " + human_bytes(current_size) + " " +
"+" + str(whole_percent) + " % bigger" + "\n")
return
else:
print("Current Value Is In Range")
if subtract_f1_f2 <0 and subtract_f1_f2 <= range_previous_day:
whole_percent = abs(subtract_f1_f2 / previous_size * 100)
print (human_bytes(previous_size) + " -> " + human_bytes(current_size) + " " + str(
whole_percent) + " % smaller" + "\n")
else:
print("Current Value Is In Range")
result = compare_sizes(1000,1400)# 40% Bigger
result = compare_sizes(1000,1399)# In Range
# result = compare_sizes(1000,599)

Python formatting print

I'm having some formatting issues with my call to print function. For lack of knowledge of better ways to format, i've ended up with an issue. here is what it should look like
However the actual result of my print returns this.
def tupleMaker(inputString):
s1 = inputString.split()
# Adding the surname at the end of the string
s2 = [s1[len(s1) - 1]]
# Number of other names(no surname)
global noOfNames
noOfNames = len(s1) - 4
# Adding all the other names
for i in range(noOfNames):
s2.append((s1[i + 3]))
# Adding the Reg number
s2.append(s1[0])
# Adding the Degree scheme
s2.append(s1[2])
# Adding the year
s2.append("Year " + s1[1])
# Making it a tuple
t = ()
for i in range(len(s2)):
t = t + (s2[i],)
return t
def formatting(t):
s1 = ""
for i in range(len(t)):
s1 += t[i]
if (i == 0):
s1 += ", "
elif (i == len(t) - 4):
s1 += " "
else:
s1 += " "
#print(t[0] + ", ", end="")
#for i in range(noOfNames):
#print (t[i+1], end= " ")
#print(format(t[1+noOfNames], "<32s"))
#print(format(thenames, "<32d") + format(regNo, "<7d") + format(degScheme, ">6s") + format(year, ">1s")
print("")
print(s1)
I would recommend looking at using pythons built in string.format() function a small tutorial is located here: https://pyformat.info/

Categories