I am trying to create a lottery loop which stops when random generated numbers match the winner ones. But I'm getting this after some time.
---------- FINISHED ----------
exit code: -1073741571 status: 1
import sys
import random
sys.setrecursionlimit(1500000)
lotteryWinner = []
lotteryRandom = []
for i in range(6):
number = random.randint(1,50)
while number in lotteryWinner:
number = random.randint(1,50)
lotteryWinner.append(number)
lotteryWinner.sort()
print(lotteryWinner)
def main():
if len(lotteryRandom)>5:
lotteryRandom.clear()
for i in range(6):
number = random.randint(1,50)
while number in lotteryRandom:
number = random.randint(1,50)
lotteryRandom.append(number)
lotteryRandom.sort()
print(lotteryRandom)
if lotteryWinner != lotteryRandom:
main()
if lotteryWinner == lotteryRandom:
print('You win')
main()
The exit code you receive occurs to indicate that the program indeed did recurse till the provided limit, however reaches the maximum number of recursions. Often it is also necessary to provide the threadinglimit. But since the program is based on random number generation, it might just work some time when a matching list is indeed found. However, it is important to understand how small a probability you are dealing with. You are trying to match 5 random numbers in the two lists which includes:
You want to generate the exact same 5 numbers.(from 1 to 50, where the chaces of picking 1 number is 1/50 and the probability of picking 5 numbers is (1/5)^5)
You want them in the same order in the list. (sorting them as you have done is a good choice)
To make the chances better, one of the multiple things you could do is
import sys
import random
sys.setrecursionlimit(1500000)
lotteryWinner = []
lotteryRandom = []
for i in range(6):
number = random.randint(1,10)
lotteryWinner.append(number)
lotteryWinner.sort()
print(lotteryWinner)
def main():
number = random.randint(1,10)
if number not in lotteryWinner:
main()
else:
print('You win')
main()
Output:
[3, 4, 6, 9, 10, 10]
You win
To improve the chances, the range for random integer generation has been reduced and the program only checks if the generated number is in the initial list of generated numbers. You could increase the range for random number generation to make winning more rare.
Related
So I am trying to get a program working for my class. I have to create a random number and then have it print off and from there I have to have it list the highest number and the lowest number. I am struggling to figure out how to get that to work.
import random
print("My Favorite Numbers")
for myFavNumbers in range(0,100,10):
myFavNumbers = random.randint(0,100)
print(myFavNumbers)
numSrch = (myFavNumbers)
for myFavNumbers in range(myFavNumbers):
if numSrch[myFavNumbers].upper()==numSrch.upper():
print(myFavNumbers[myFavNumbers])
it is a screenshot of the error
I hope I understood your task correctly. Is highest = max? Is lowest = min?
import random
random_numbers = []
print('My random numbers:')
for _ in range(10):
random_numbers.append(random.randint(0, 100))
print(random_numbers[-1])
print()
print(f'Max one: {max(random_numbers)}')
print(f'Min one: {min(random_numbers)}')
Try this Code:
import random
print("My Favorite Numbers")
listofstud=[]
for myFavNumbers in range(0,100,10):
myFavNumbers = random.randint(0,100)
listofstud.append(myFavNumbers)
print("List of Student:"+str(listofstud))
print("Max Number:"+str(max(listofstud)))
print("Max Number:"+str(min(listofstud)))
this code will give max and min num from list
From what I understand, your assignment is asking you to:
Generate a bunch of random numbers.
Remember those random numbers.
Print out the numbers and find the highest and lowest numbers.
Right now, what your code is doing is:
Generating a bunch of random numbers and printing out each individual number.
Remembering only the last number.
Rather than saving the last number, you need to find a way record each number as it passes by. That is, you need to store the numbers in a list.
Once you've built a list of random numbers, you can use Python's built-in functions to do the rest of the work for you.
So, given all that, see if this code makes sense:
import random
print("My Favorite Numbers")
favoriteNumberList = []
for _ in range(0,100,10):
myFavNumber = random.randint(0,100)
favoriteNumberList.append(myFavNumber)
print(favoriteNumberList)
print(max(favoriteNumberList))
print(min(favoriteNumberList))
Last night I was thinking to my self about the probability of getting the same outcome in "Rock, Paper, Scissors" 10 times in a row. I worked out how to do that and completed that task but then I wanted to challenge myself a bit, so I wanted to adapt the program so it ran the initial program a number of times (10,000) and then outputted the average result, which I hoped would be close to the probability of getting the same 10 times in a row. Please note that I am not taking into account tactics, just that both players randomly pick either r, p, or s.
def rps():
num=0 # num is the number of times i want the programme to run while roll<10:
total=0 # this should be close to 3^10 * 10000, its the result of all the tries added together
while num <10001:
tries=0 # this is how many times the programme has tried to get p1=p2
roll=0 # this is the amount of times it has counted p1=p2 (it gets re-set everytime it reaches 10)
import random
while roll <10:
p1=random.randint(1,3)
p2=random.randint(1,3)
if p1==p2:
roll=roll+1
else:
tries=tries + 1
roll=0
num=num+1
if roll==10:
total=total+roll
roll=0
if num==10000:
print (num)
print (total/num)
rps()
There are quite a few problems with the program, for once, there isn't any use for the second for loop, I get that you are using the second for loop to reset the counter if the number of consecutive rolls reaches 10, but you are already doing that here
if roll==10:
total=total+roll
roll=0
by setting roll=0, you are resetting it.
also, the last if condition adds to the complexity,
if num==10000:
print (num)
print (total/num)
instead of this, you can just print the average outside the loop like this
if roll==10:
total=total+roll
roll=0
print (total/10000) #this being outside the while loop
one more thing, you are incrementing num only when roll1 != roll2, this adds to the number of times the loop has to run
This is how the program came out after the changes
import random
def rps():
num=0 #num is the number of times i want the programme to run while roll<10:
total=0 #this should be close to 3^10 * 10000, its the result of all the tries added together
roll = 0
while num <10001:
tries=0 #this is how many times the programme has tried to get p1=p2
p1=random.randint(1,3)
p2=random.randint(1,3)
if p1==p2:
roll = roll+1
else:
tries = tries + 1
roll = 0
if roll==10:
print(roll)
total += roll
roll=0
num = num + 1
print (total/10000)
print(tries)
rps()
The answer coming out was 0,I guess it was highly unlikely that you get 10 in a row.
Some self-explanatory code (so you can also learn to write clean code):
import random
def get_10_outcomes():
return [
(random.randint(1, 3), random.randint(1, 3))
]
def have_we_got_10_in_a_row():
return (
len(set(get_10_outcomes()))
== 1
)
def how_many_10_in_a_row_in_10000():
return len(list(filter(
None,
[have_we_got_10_in_a_row() for _ in range(10000)]
)))
def get_chance_of_10_in_a_row():
return how_many_10_in_a_row_in_10000() / 10000
chance = get_chance_of_10_in_a_row()
print('{:.3%}'.format(chance))
I'm making a simple lottery simulator. I have two mutually exclusive command line flags, so either the program performs amount of draws the user specifies or until you hit the Jackpot.
for i in range(args.draws):
perform lottery draws here
How to modify the for loop in a way that if args.draws is not given it should
run until jackpot is hit. I am now defaulting the args.draws to a very high number
so in almost all the cases the Jackpot is hit and then break the loop, but is there
better way to do this
Here is the whole code. It is not pretty Im just learning Python
import random
import argparse
def oneoutof(occurance, times):
if occurance == 0:return 0
return float(times)/float(occurance)
if __name__ == '__main__':
LOTTERY_NUMBERS = [i + 1 for i in range(39)]
WIN_LIST =[0,0,0,0]
six_plus_one = 0
parser = argparse.ArgumentParser(description="[Lottery]\n"
"Example: python3 lottery.py ")
group = parser.add_mutually_exclusive_group()
group.add_argument("-s","--seven",action="store_true",
help="Stop when you hit 7 right")
group.add_argument("-d","--draws",type=int,default=1000000,
help="Stop after number of draws")
parser.add_argument("-n","--numbers", nargs=7, type = int,choices=range(1, 40),
help="Lottery numbers, if not given will be randomly selected")
args = parser.parse_args()
if args.numbers ==None:
print('You did not give lottery numbers so following numbers are randomly selected')
picked_numbers = set(random.sample(LOTTERY_NUMBERS, 7))
print(*picked_numbers)
print('Number of lottery draws is {:,}'.format(args.draws))
else:
picked_numbers = set(args.numbers)
print('Number of lottery draws is {:,}'.format(args.draws))
for i in range(args.draws):
lotto_numbers = set(random.sample(LOTTERY_NUMBERS, 7))
remaining_nbrs = set(LOTTERY_NUMBERS).difference(lotto_numbers)
extra_nmbs = set(random.sample(remaining_nbrs, 3))
correct_numbers = lotto_numbers&picked_numbers
correct_extranmbs = extra_nmbs&picked_numbers
if len(correct_numbers) > 3 and not (len(correct_numbers) == 6 and correct_extranmbs):
index = len(correct_numbers) - 4
WIN_LIST[index] = WIN_LIST[index] + 1
if len(correct_numbers) == 7 and args.seven:
print("You hit JACKPOT {} round".format(i))
break
elif len(correct_numbers) == 6 and correct_extranmbs:
six_plus_one=six_plus_one+1
print('4 correct %i times, one out of %g\n'
'5 correct %i times, one out of %g\n'
'6 correct %i times, one out of %g\n'
'6+1 correct %i times, one out of %f\n'
'7 correct %i times, one out of %f\n'
%(WIN_LIST[0],oneoutof(WIN_LIST[0], args.draws),
WIN_LIST[1],oneoutof(WIN_LIST[1], args.draws),
WIN_LIST[2],oneoutof(WIN_LIST[2], args.draws),
six_plus_one,float(args.draws)/float(six_plus_one) if six_plus_one else 0,
WIN_LIST[3],oneoutof(WIN_LIST[3], args.draws)))
We need an import at the top of the file:
from itertools import count, islice
Then we can edit some of your code...
Firstly, set the default value of args.draws to be None - we can use this as "no limit".
group.add_argument("-d","--draws", type=int, default=None, help="Stop after number of draws")
Then, we adjust your print to take into account that None can't be formatted as a integer so we replace it with the largest possible number float('inf') which will successfully still display as inf when printed with the {:,} formatting, so:
print('Number of lottery draws is {:,}'.format(args.draws or float('inf')))
Then, instead of looping over a range, we loop over an infinite sequence, but cap it to n many elements, which is either an integer or is None (which means don't apply a limit to that sequence):
for i in islice(count(1), args.draws):
# ...
You can use a while loop instead.
if(args.draws.length!=0)
for i in range(args.draws):
perform lottery draws here
else
while(!jackpotHit)
perform lottery draws here
I would use itertools.count:
from itertools import count
draws = range(args.draw) if args.draw is not None else count()
for i in draws:
perform lottery draws here
I'm very new to Python and I hope for some help or guides by asking here.
Here's the problem:
Write a program that estimates the average number of drawings it takes before the user’s numbers are picked in a lottery that consists of correctly picking six different numbers that are between 1 and 10. To do this, run a loop 1000 times that randomly generates a set of user numbers and simulates drawings until the user’s numbers are drawn. Find the average number of drawings needed over the 1000 times the loop runs.
I tried to create something (below), but I just can't think of how to get those average number. Also it seems the loop is not good. Any help or solution? thank you in advance.
from random import randint
from random import choice #???
userlist = []
for y in range(6):
user = input("Enter your entry no.{} lotto number: ".format(y+1))
userlist.append(user)
x = 0
randomlotterylist = []
while not x>1000:
lottery = []
for i in range (6):
lot.append(randint(1,10))
randomlotterylist.append(lottery)
x = x + 1
#Next.. ????
First, you want to know your theoretical average number of drawings, that's (1/10)^6 assuming no repetition allowed. Therefore on average every 1,000,000 tries you'd hit the correct number. That is only if the order matters but I assume in your case the order does not matter, so def your average is less than that...
from random import randint
def number_of_tries_before_hitting_jackpot(user_number):
n_tries = 0
while True:
random_number = set([randint(1,10) for i in range(1,7)])
if user_number == random_number:
return n_tries
else:
n_tries+=1
def ask_user_his_number():
userlist = []
for y in range(6):
user = input("Enter your entry no.{} lotto number: ".format(y+1))
userlist.append(user)
return set(userlist)
n_tries_list = []
for x in range(1,1001):
user_number = ask_user_his_number()
print user_number
tmp = number_of_tries_before_hitting_jackpot(user_number)
print tmp
n_tries_list.append(tmp)
avg_number_drawings = reduce(lambda x, y: x + y, n_tries_list) / len(n_tries_list)
print avg_number_drawings
This code is not what I'd do in the sense that the user needs to input its 6 numbers 1,000 times (v annoying for the user). You could change the ask_user_his_number function to a function that just randomly selects a set of 6 numbers.
by using random module, for loop, list in short without defining fuction.
from random import *
user_num=[]
count=0
for i in range(6):
random_num=randint(1,10)
user_num+=[random_num]
user_num.sort()
for j in range(1000):
picked=[]
for k in range(6):
pick_num=randint(1,10)
picked+=[pick_num]
picked.sort()
if picked==user_num:
count+=1
print("the avg darwing is: ",count, count/1000)
So I'm creating a very basic python game and I need some help with this step I'm stuck at. The concept of the game is for the program to roll two die and add the sums. With that number they can choose a number available from the number list (1-10) to "peg". They keep going until all numbers are pegged or are out of options. Earlier in the program I created two functions that I'm using in this step. Those two are ask_number and valid_moves. Basically the ask number just asks them which number they want to peg but it doesn't actually peg the number yet. The valid_moves function just checks which numbers are still available for the player to select.
The game pretty much just looks like this halfway through:
------------------------------
(1)(2)(3)(4)(X)(6)(7)(X)(9)(X)
------------------------------
The X are the numbers that were already pegged. In this part of the game I need to figure out how to replace the number with "X". I have this so far but I know I am way off and I am having trouble with figuring out what to do. (pegholes is the name of the list and move is the number they picked in the ask_number function). Thanks so much!
PEGGED = "X"
def enter_peg(pegholes, roll, total):
ask_number()
if ask_number == valid_moves():
pegholes.append(ask_number(PEGGED))
return pegholes, move
I am really not sure how your game is supposed to work, but this may help you out:
#!/usr/bin/env python
import random
import sys
pegs = range(2, 11)
def roll_dice():
return random.randint(1, 5) + random.randint(1, 5)
while True:
roll = roll_dice()
print "You rolled %s" %roll
available_choices = set(p for p in pegs if p != 'X') - set(range(roll+1, 11))
if len(available_choices) == 0:
print "FAIL SAUCE"
sys.exit()
while True:
choice = raw_input("Choose a number %s: " % (", ".join(str(x) for x in sorted(list(available_choices)))))
if choice == 'q':
sys.exit()
choice = int(choice)
if choice in available_choices:
break
print "Nice try buddy... pick a number in range, that hasn't been picked"
pegs[choice - 2] = 'X'
print "".join("(%s)" % p for p in pegs)
if len([x for x in pegs if x == 'X']) == 9:
print "WINNER!"
sys.exit()
I'm not clear on what you're trying to do...
When you say "add the sum" you mean add them together to get a sum, right?
Standard dice add up to 12 and two dice can't total 1 so for a fair game you want to go from 2 - 12
You could try something like this:
import random
#set up list of numbers from 2 to 10
numlist = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
#create a roll dice function, producing the sum of two random integers 1-6
def rolldice():
return (random.randint(1,6) + random.randint(1,6))
#run the rolldice function
roll = rolldice()
#set up a loop for while the sum of the roll appears in the list
while roll in numlist:
print "Your rolled %s" %roll
print "Your list was", numlist
print "Replacing %s with X" %roll
numlist[numlist.index(roll)]="X"
print "Your new list is", numlist
raw_input("Press enter to roll again")
roll = rolldice()
#once a roll not in the list show up:
print "Your roll was %s" %roll
print "This is not in your list"
You could also add another if statement to ask the user if they want to try again if the roll is not on the list... and then go back through the while loop.
Keep trying -- I was new to all of this last summer and am still learning. Just keep trying different things... you will learn from your mistakes.