My instructions: Write a program that “flips” a coin repeatedly and displays the results to the screen.
The program only stops when a specific # of heads has been flipped. That number of heads is specified by the user.
Your program should output the total number of flips made during execution.
My question is that I don’t know how long to generate Heads or Tails separately in a random manner. Im not sure how to incorporate a while or for loop in this or a counter either. Im very confused on what to do.
My code: (it’s botched because I really don’t know how what I should write)
import random
tails1= 0
heads= 1
heads_flips= int(input("Enter the amount of flips for heads:"))
while tails1 < heads_flips:
if heads_flips > 0 print Heads amount of head_flips
print("Heads", heads_flips)
There are multiple ways to solve this problem, but considering you are a beginner.
import random
tail = 0
head = 1
number_of_heads = 0
heads_flips= int(input("Enter the amount of flips for heads:"))
while number_of_heads < heads_flips:
flip = random.randrange(2)
if flip == head:
number_of_heads += 1
print("Heads", number_of_heads)
In essence, you are going to generate a random number, either 0 or 1 with random.randrange(2). We have set that 0 will represent that it was tails and 1 that it was heads.
The variable number_of_heads is increased every time 1 was generated, and eventually, it will make the condition of our while loop becomes False.
Related
I am attempting to make a script in Python/Jupyter Notebook(anaconda3).
the goal of the script is to flip a coin N(very large positive integer value) times.
i want it to track the results of the total flips, either all 1s, or not.
i need the function to do this for every column in a matrix parent matrix, which i am struggling to perform.
Any and all help is appreciated
originally i thought
N=C
F=secrets.randbelow(2)**C
would work, but this is just 1 or 0 to that power, and not
F=secrets.randbelow(2)*secrets.randbelow(2)secrets.randbelow(2)...
like im looking for
this is the crude code i have to tally and track the final value
Heads=0
Q=np.zeros(N)
for i in range(N):
Q[i]=secrets.randbelow(2)
print (Q)
for i in range(N):
if Q[i]==1:
Heads=Heads+1
if Heads==N:
print ('Verify')
else:
print('vote')
the issue is that i need this protocol to be performed every single time a new column of A is selected
ideally, it would be in a for loop that steps through A
for col in A:
coin flip matrix is determined and results calculated
if calculated value ==0:
else:
I'm a beginner, new both to coding and to Python and I'm using the book "Automate the boring stuff with Python" to learn; one of the practice projects of the first chapters is the following:
Write a program to find out how often a streak of six heads or a streak of six tails comes up in a randomly generated list of heads and tails. Your program breaks up the experiment into two parts: the first part generates a list of randomly selected 'heads' and 'tails' values, and the second part checks if there is a streak in it. Put all of this code in a loop that repeats the experiment 10,000 times so we can find out what percentage of the coin flips contains a streak of six heads or tails in a row.
My programm returns exactly double as much percentage as it should. (Expected: 79-80%, returned 159%). I've tried to fix my code by comparing it with the other replies I've found but, since I've used a different approach, I still don't understand why this happens, as everything looks right.
import random
Total = [] # Defines the list in which there will be all of the throws
Throw = ("H", "T") # Cases
for x in range(10000): # Repeats the 100 throws 10 000 times
for i in range(100):
Total.append(random.choice(Throw)) # Adds a random throw to the list "Total";
Join = " ".join(Total) # Creates a string to easily count the groups of T and H
N_T = Join.count("T T T T T T") # Counts the Numbers of groups of six Tails
N_H = Join.count("H H H H H H") # Counts the Numbers of groups of six Heads
print('Chance of streak: %s%%' % ((N_H + N_T) / 100)) # Probability
I hope this wasn't a dumb question... Thank you for your help.
You need to set borders for your search terms, like this:
N_T = Join.count("H T T T T T T H") # Counts the Numbers of groups of six Tails
N_H = Join.count("T H H H H H H T") # Counts the Numbers of groups of six Heads
because otherwise what would happen if you have the following sequence:
"T T T T T T T T T T T T"
It can find your pattern multiple times in that bigger sequence, which leads to more hits than 100%, which of course is plausible in that case.
The question I'm solving is if I receive 1/5 coupons at random a day, how many days will it take to collect 2 copies of each of the 5 coupons?
My code is only checking for 1 of each coupon instead of two but I'm not sure where I can make revisions. I edited the while True statement to include a list to my cards_own statement like this cards_own != [1,1,2,2,3,3,4,4,5,5] but then my output didn't print at all. I think maybe using the random.choice function would be a better option. Any recommendations?
import numpy as np
# number of simulations
n =10000
# defining function to check if we got all 5 cards indexed from 0 to 4
def all_cards(arr2,arr1=np.array(range(5))):
return np.array_equal(arr1,arr2)
days_taken = 0
# performing simulation
for i in range(n):
# initializing empty list to store card obtained in each day
cards_own =[]
# days taken in each simulation
days =1
# looping until i get 5 cards and count the days taken for finding average
while True:
value = np.random.randint(0,5)
cards_own.append(value)
if len(cards_own)>=5:
if all_cards(arr2=np.array(list(set(cards_own)))):
days_taken+=days
break
days+=1
average = days_taken/n
# recording the result in result with given precision
result = round(average,2)
print("Average days taken = ",result," days")
So there are a few things that I think you could change here. First off you can change your if statement to read if len(cards_own) >= 10 since you need at least ten coupons to have 2 of everything. Additionally, in your cards_all function, you can loop through all of the possible coupons (in this case [0, 4] and check if there are at least two occurences for each of them in the array (so you don't need arr2). Something like:
for i in range(5):
if np.sum(arr1 == i) < 2:
return False
return True
the if statement is just counting how many times the element i appears in the array. Also you should not be converting arr1 to a set in the function call since sets cannot have duplicate values so checking for 2 of each coupon would never work like that. Hopefully this helps!
I'm creating a program that provides the user with job offers. For example they're given 10 offers and they decide to reject the first 3 right off the bat. From there I'm taking the maximum number out of the three and I want to accept the next best offer. Although my program is accepting the best offer instead of the next best.
To explain a little further, let's say offer 4 was higher than the max number out of the first 3, I want that offer to be considered 'accepted' even if offer number 5 is higher. Here is my code at the moment, the problem lies that the last 'if' statement keeps repeating causing it to give me the best offer instead of next best.
offerRejList = []
offerList = []
counter = 1
counterRej = 1
while counter <= jobOff:
offer = random.gauss(65, 5)
offerList.append(offer)
if counterRej <= jobRej:
offerRejList.append(offer)
print('Offer #' ,counter, ': $',offer,'-',)
counterRej += 1
counter += 1
if offer > max(offerRejList):
acceptedOffer = offer
http://www.tutorialspoint.com/python/python_loop_control.htm
That's all you need. Immediately after you have "acceptedOffer"
Friends and I were wondering what the % chance of victory was in various situations in the board game, Risk, which involves a world war over an Earth-like board divided into territories.
For those unfamiliar with Risk:
In each turn of the game an attacker can decide to invade a defender's country on the board. The attacker and defender choose how many dice to use for the battle. For example the attacker can in some situations decide to attack with 3 dice and the defender might choose to defend with 2 dice.
Attacker rolls 3 dice and gets 6,4,1
Defender rolls 2 dice and gets 6,3
If the same number is rolled, defender always wins, so in this situation,
we compare the attacker's two highest rolls against the defender's.
The defender's 6 beats the attacker's 6 and
the attacker's 4 beats the defender's 3.
In this case each side loses 1 army. This could continue with more dice rolls until the attacker stops attacking or runs out of armies, but at this point I am only interested in the frequency of wins on single tosses of the dice.
So I wrote a batch to simulate many times rather than entering the counterintuitive world of probabilities. I'm fairly new to coding so I'm looking for tips on efficiency. I am yet to fathom multiprocessing so we'll leave that out for now if that's ok.
I was surprised at how long it took to do one million simulations (around 20 seconds) and was wondering if there's something I'm doing wrong or if this is the sort of time you might expect from such a routine.
Here's the simulation part:
from random import randint
# Pass in number of each dice and number of sim's
def simulate(attDice,defDice,rolls):
attLosses = 0
defLosses = 0
for roll in rolls: # Number of simulations
attRolls = [] # List holding attack dice 'scores'
for die in range(attDice): # Number of attack dice rolled
attRolls.append(randint(1,6))
defRolls = [] # List holding defence dice 'scores'
for die in range(defDice): # Number of defence dice rolled
defRolls.append(randint(1,6))
while len(attRolls) and len(defRolls): # For each
if max(attRolls) > max(defRolls): # Att's must beat def's
defLosses += 1
else:
attLosses += 1
# Delete the highest number from each list
del(attRolls[attRolls.index(max(attRolls))]) # This seems clumsy
del(defRolls[defRolls.index(max(defRolls))]) # which is what makes me
# think there's a better way
return attLosses,defLosses
# We then go and work out percentages etc.
Lots of handwaving, totally unrigorous answer.
I'm not surprised with ~20s for one million rounds. I've done similar experiments/simulations in Python with the same experience. Granted, those experiments are not really time critical so I did not optimize.
And Python isn't really known for speed. Maybe you're used to lower-level languages. If you did the same experiment in Java, I would be surprised if it took you as long.
(If you really want to speed this up, maybe some context in your question will help? Your purpose seems casual so aside from some constant-time speed-ups and maybe some micro-optimizations, I see little to change.)
Since you are in effect sorting the dice lists, it is better to use python's sort function which is fast.
Generating random numbers is also relatively slow. By only generating one number for all the dice you can accelerate it somewhat.
This runs in ~5s on my computer for a million rolls if attDice and defDice are smallish (<=5). (With PyPy it runs in 1s.)
def freqs(attDice, defDice, rolls):
m = min(attDice, defDice)
freq = [0]*(m+1)
for i in range(rolls):
ar = random.randrange(6**attDice)
dr = random.randrange(6**defDice)
ad = [(ar / 6**j) % 6 for j in range(attDice)]
ad.sort(reverse=True)
dd = [(dr / 6**j) % 6 for j in range(defDice)]
dd.sort(reverse=True)
aws = sum(j > k for j, k in zip(ad, dd))
freq[aws] += 1
return freq
It returns a frequency table of attacker wins.
Here's the start of a numpy implementation for 1,000,000 rolls.
I've marked this community wiki if someone wants to expand it, edit away.
3 attack dice, 2 defend dice
import numpy
A = numpy.random.randint(1,6,size=(1000000,3)).sort()
D = numpy.random.randint(1,6,size=(1000000,2)).sort()
Ahigh = A[:,2]
Dhigh = D[:,2]
Awins1st = (Ahigh > Dhigh)
A2nd = A[:,1]
D2nd = D[:,1]
Awins2nd = (A2nd > D2nd)
# needed: tabulate results, remove smelly repeating code, generalize
Awins1st and Awins2nd are 1000000 element true/false arrays, indicating whether the attacker won the 1st or 2nd "battle" from comparing the 3 A dice to the 2 D dice.