I was working on Python Crash Course, exercise 9-15: 'Lottery Analysis'. It took me a very long time to get it to work. The reason it took that long is I wanted to use my existing class from the previous exercise 9-14 which used choices()
method not choice()
. I have looked at the author's and some other solutions but still don't get the logic behind those solutions, especially incrementing and then showing the number of attempts it took to win. I have looked at the book's material over and over again and still couldn't get it to work using choice()
on my own. Until I found a few articles talking about different methods for using random
. I went over those articles and finally got the other exercise 9-14 to work.
First, I want to know what I did is normal for anyone who just started learning Python with no coding background. Am I complicating things to work this way? How can I get my code, see below, to work using choice()
? Can the following code be simplified with fewer lines?
Any advice is much appreciated!
Full code
from random import choices
class WinningTicket:
"""
Randomly select characters to generate tkt numbers.
Take a tkt no. and see how many tries it will take to win.
"""
def __int__(self, selection, final):
"""Initializing attributes."""
self.selection = selection
self.final = final
def generate_tkt(self, length):
"""Randomly select a series of characters to generate tkt num."""
series = ["a", "b", "c", "d", "e", 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
self.selection = choices(series, k=length)
self.final = "".join(map(str, self.selection))
return self.final
def pull_tkt(self, my_tkt):
attempt_num = 0
while self.generate_tkt(len(my_tkt)):
attempt_num += 1
if self.final == my_tkt:
print(f"\nYou've won with tkt no. {self.final}")
print(f"It took {attempt_num} tries to win.\n")
break
else:
print(f"Trying to win: attempt no. {attempt_num}")
Create obj and call method
tkt_num = WinningTicket()
tkt_num.pull_tkt("45da")
Results
.
.
.
.
Trying to win: attempt no. 4138
Trying to win: attempt no. 4139
Trying to win: attempt no. 4140
Trying to win: attempt no. 4141
Trying to win: attempt no. 4142
Trying to win: attempt no. 4143
You've won with tkt no. 45da
It took 4144 tries to win.