Python: Average number of drawings (Randomly generated numbers) - python

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)

Related

Collecting multiple unknown inputs

Alright so this problem has been grinding me for a good hour. I am taking a zybooks course and I'm presented with the prompt,
Statistics are often calculated with varying amounts of input data. Write a program that takes any number of integers as input, and outputs the average and max.
Ex: If the input is:
15 20 0 5
the output is:
10 20
currently I have it 'working' with my code but the issue is I cannot figure out how to keep the input open for more or less inputs as zybooks runs through multiple different tests. i'm sure its something simple im overlooking. anything helps!
nums = []
for i in range(0, 4):
number = int(input('Enter number'))
nums.append(number)
avg = sum(nums) / len(nums)
print(max(nums), avg)
This code continually asks the user to enter values until they enter a blank (just press enter without typing).
This is the code:
nums = []
# initialse
number = 0
# loop until there isn't an input
while number != "":
# ask for user input
number = input('Enter number:')
# validate the input isn't blank
# prevents errors
if number != "":
# make input integer and add it to list
nums.append(int(number))
avg = sum(nums) / len(nums)
print(max(nums), avg)
Alternatively, if you have the list of numbers:
def maxAndAvg(nums):
avg = sum(nums) / len(nums)
return max(nums), avg
One solution is to have the user specify how many numbers they want to take the average of. For instance:
nums = []
n = int(input('How many numbers: '))
for i in range(n):
number = int(input('Enter number: '))
nums.append(number)
avg = sum(nums) / n
print(max(nums), avg)
Alternatively, if you want a function that itself takes a variable number of arguments, you'll need to use the "*args" operator. For instance,
def my_average(*args):
return sum(args)/len(args)
An example usage:
print(my_average(1),my_average(1,2),my_average(1,2,3))
Result:
1.0 1.5 2.0
Ok, guys this is the correct code to figure this lab out. Did some data mining and some line manipulation to pass all ten tests:
nums = []
while not nums:
number = input()
nums = [int(x) for x in number.split() if x]
avg = int(sum(nums) / len(nums))
print(avg, max(nums))

I have to generate random integers in python, but the user has to say how many integers they want to generate [duplicate]

This question already has answers here:
Generate 'n' unique random numbers within a range [duplicate]
(4 answers)
Closed 2 years ago.
I have to ask the user how many numbers they want to generate and then i can generate integers according to them in the range of 0 to a 100. If the user wants 5 numbers I have to generate 5 random numbers, but have no clue how.
input("How many numbers should the string consist of? ") #The user gives a number
for i in range(4): # I used a 4 but its going to be the users input
print(random.randint(0, 100)) #The integers will print
Afterwards I have to calculate the total of all the integers generated,
The total is: sum of generated integers.
from random import randint
def random_generate(count: int):
for _ in range(count):
yield randint(0, 100)
for num in random_generate(20):
print("random number is:", num)
Change the for i in range loop iteration count to the number of integers the user wants:
num = int(input("How many numbers should the string consist of? "))
for i in range(num):
print(random.randint(0, 100)) #The integers will print
Afterwards I have to calculate the total of all the integers generated, The total is: sum of generated integers.
Add a variable to count all the integers, in this case it is count:
num = int(input("How many numbers should the string consist of? "))
count=0
for i in range(num):
randomnumber = random.randint(0, 100)
print(randomnumber)
count += randomnumber
print(count)
Looks like i posted at the same time as Daniil
To add to Daniils answer:
You could also do a validation for when the user does not enter an integer it gets promted again.
import random
while True:
try:
user_input_str = input("How many numbers should the string consist of?") #The user gives a number
num = int(user_input_str)
break
except ValueError:
print(f"{user_input_str} is not an integer, please enter an integer)")
total_sum = 0
for i in range(num): # I used a 4 but its going to be the users input
random_int = random.randint(0, 100)
print(f"#{i} Random int: {random_int}")
total_sum = total_sum + random_int
print(f"Total sum: {total_sum}")

Trying to create lottery program in python but getting "FINISHED"

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.

Calculating an average in "Rock, Paper, Scissors"

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))

Using random.randint help in python

The following code is my attempt at simulating a lottery.
import random
def lottery(numbers):
lottoNumbers = [randint('0,100') for count in range(3)]
if numbers == lottoNumbers:
print('YOU WIN $10,000')
else:
print('YOU LOSE,DUN DUN DUNNN!')
return numbers
def main():
numbers = int(input('Enter a number: '))
if numbers == lottoNumbers:
numbers = lottery(numbers)
else:
numbers = lottery(numbers)
main()
Hey guys I've gotten this far with the help you've given me. I'm trying to write the code so that 3 lotto numbers at random will be chosen. Then the user must enter 3 of his/her own lotto numbers. If they get all 3 correct then they win the whole prize, if they get the 3 numbers but not in the correct order they win some of the prize. Obviously if they guess all wrong then a print statement would state that. What I'm confused about is how can I write the code so that the user can enter 3 numbers to try matching the random lottery numbers. I also want to print the 3 lottery numbers after the user inputs his/her choices. Any ideas guys?
Thanks for your help everyone.
You seem a bit confused about what the role of the arguments in a function are. You've said that your randm function takes the argument "number", but then you haven't actually used it anywhere. The next time number appears, you've assigned it a completely new value, so any value passed to randm isn't actually being used.
Also, the function is trying to return x, when x hasn't been assigned within the function. Either you already have a global variable called x already defined, in which case the function will just return that variable, or the function will just fail because it can't find the variable x.
Here's a quick example I've done where you pass their three numbers as a list as an argument to the function.
import random
theirNumbers=[5,24,67]
def checkNumbers(theirNumbers):
lottoNumbers = []
for count in range(3)
lottoNumbers.append(random.randint(0,100))
winning = True
for number in theirNumbers:
if not each in lottoNumbers: winning=False
if winning == True: print("Winner!")
There are a few things wrong with your implementation, to name a few:
if you are trying to compare the output of the function randm to x, you will need to include a return value in the function, like so:
def randm():
return return_value
You appear to be printing all the values but not storing them, in the end you will only end up with the final one, you should attempt to store them in a list like so:
list_name = [randint(0,100) for x in range(x)]
This will generate randint(0,100) x times in a list, which will allow you to access all the values later.
To fix up your code as close to what you were attempting as possible I would do:
import random
def randm(user_numbers):
number = []
for count in range(3):
number.append(random.randint(0, 100))
print(number)
return user_numbers == number
if randm(x):
print('WINNER')
If you are looking for a very pythonic way of doing this task,
you might want to try something like this:
from random import randint
def doLotto(numbers):
# make the lotto number list
lottoNumbers = [randint(0,100) for x in range(len(numbers))]
# check to see if the numbers were equal to the lotto numbers
if numbers == lottoNumbers:
print("You are WinRar!")
else:
print("You Lose!")
I'm assuming from your code (the print() specifically) that you are using python 3.x+
Try to post your whole code. Also mind the indentation when posting, there it looks like the definition of your function would be empty.
I'd do it like this:
import random
def lottery():
win = True
for i in range(3):
guess = random.randint(1,100)
if int(raw_input("Please enter a number...")) != guess:
win = False
break
return win
Let so do this in few steps.
First thing you should learn in writing code is to let separate pieces of code( functions or objects) do different jobs.
First lets create function to make lottery:
def makeLottery(slotCount, maxNumber):
return tuple(random.randint(1,maxNumber) for slot in range(slotCount))
Next lets create function to ask user's guess:
def askGuess(slotCount, maxNumber):
print("take a guess, write {count} numbers separated by space from 1 to {max}".format(count = self.slotCount, max = self.maxNumber))
while True: #we will ask user until he enter sumething suitable
userInput = raw_input()
try:
numbers = parseGuess(userInput,slotCount,maxNumber)
except ValueError as err:
print("please ensure your are entering integer decimal numbers separated by space")
except GuessError as err:
if err.wrongCount: print("please enter exactly {count} numbers".format(count = slotCount))
if err.notInRange: print("all number must be in range from 1 to {max}".format(max = maxNumber))
return numbers
here we are using another function and custom exception class, lets create them:
def parseGuess(userInput, slotCount,maxNumber):
numbers = tuple(map(int,userInput.split()))
if len(numbers) != slotCount : raise GuessError(wrongCount = True)
for number in numbers:
if not 1 <= number <= maxNumber : raise GuessError(notInRange = True)
return numbers
class GuessError(Exception):
def __init__(self,wrongCount = False, notInRange = False):
super(GuessError,self).__init__()
self.wrongCount = wrongCount
self.notInRange = notInRange
and finally function to check solution and conratulate user if he will win:
def checkGuess(lottery,userGuess):
if lottery == userGuess : print "BINGO!!!!"
else : print "Sorry, you lost"
As you can see many functions here uses common data to work. So it should suggest you to collect whole code in single class, let's do it:
class Lottery(object):
def __init__(self, slotCount, maxNumber):
self.slotCount = slotCount
self.maxNumber = maxNumber
self.lottery = tuple(random.randint(1,maxNumber) for slot in range(slotCount))
def askGuess(self):
print("take a guess, write {count} numbers separated by space from 1 to {max}".format(count = self.slotCount, max = self.maxNumber))
while True: #we will ask user until he enter sumething suitable
userInput = raw_input()
try:
numbers = self.parseGuess(userInput)
except ValueError as err:
print("please ensure your are entering integer decimal numbers separated by space")
continue
except GuessError as err:
if err.wrongCount: print("please enter exactly {count} numbers".format(count = self.slotCount))
if err.notInRange: print("all number must be in range from 1 to {max}".format(max = self.maxNumber))
continue
return numbers
def parseGuess(self,userInput):
numbers = tuple(map(int,userInput.split()))
if len(numbers) != self.slotCount : raise GuessError(wrongCount = True)
for number in numbers:
if not 1 <= number <= self.maxNumber : raise GuessError(notInRange = True)
return numbers
def askAndCheck(self):
userGuess = self.askGuess()
if self.lottery == userGuess : print "BINGO!!!!"
else : print "Sorry, you lost"
finally lets check how it works:
>>> lottery = Lottery(3,100)
>>> lottery.askAndCheck()
take a guess, write 3 numbers separated by space from 1 to 100
3
please enter exactly 3 numbers
1 10 1000
all number must be in range from 1 to 100
1 .123 asd
please ensure your are entering integer decimal numbers separated by space
1 2 3
Sorry, you lost
>>> lottery = Lottery(5,1)
>>> lottery.askAndCheck()
take a guess, write 5 numbers separated by space from 1 to 1
1 1 1 1 1
BINGO!!!!

Categories

Resources