In my Python program I want to roll a dice 8 times, but without it repeating the same value. I am trying different things but can't find a solution. My code is all follows:
if time%2 == 0 and counter_agents<max_agents:
succeeded=False
teller=0
while (not(succeeded)and teller<10):
dice = random.randint (0,7)
combis = []
if dice == 0:
pos_x=20
pos_y=75
elif dice == 1:
pos_x=21
pos_y=75
elif dice == 2:
pos_x=60
pos_y=75
elif dice == 3:
pos_x=61
pos_y=75
elif dice == 4:
pos_x=100
pos_y=75
elif dice == 5:
pos_x=101
pos_y=75
elif dice == 6:
pos_x=140
pos_y=75
elif dice == 7:
pos_x=141
pos_y=75
if counter_agents+1<=max_agents: #field[pos_y,x_pos]==0 and
succeeded=True
teller=teller+1
I believe this function does the job
import random
def roll_dice(min, max) -> int:
numbers = set()
for _ in range(max - min + 1):
while (dice_value := random.randint(min, max)) in numbers:
pass
numbers.add(dice_value)
yield dice_value
You can call it like this:
dice = roll_dice(0, 7)
dice_value = next(dice)
To get all values:
list(roll_dice(0, 7))
You can use this:
#Importing the library
import numpy as np
#create a function "def"
def roll():
numbers = list(np.random.choice(range(8), 8, replace=False))
return numbers
#calls the function
roll()
Related
I have the logic down for this game of craps. My only problem right now is that I can't seem to get any output for finding the probability of wins for the game. Here is the code:
from random import seed, randint
def simulate():
die1 = randint(1, 6)
die2 = randint(1, 6)
roll = die1 + die2
first_roll = roll
if first_roll == 7 or first_roll == 11:
return True
elif first_roll == 2 or first_roll == 3 or first_roll == 12:
return False
else:
second_roll = randint(1, 6) + randint(1, 6)
while second_roll != first_roll and second_roll != 7:
if second_roll == first_roll:
return True
elif second_roll == 7:
return False
## Main
def probability(n):
simulate()
wins = 0
for i in range(n):
if simulate() == 1:
wins += 1
return
print(probability(10000))
I want to find the probability of wins for 10000 trials. However, I don't get any output when running this code. Nothing shows up. Where am I going wrong on this? I have tried for a couple hours but nothing seems to be working for me. Please include code and what I was doing wrong. I know for a fact that it should be 49% but I can't seem to arrive at that answer.
I am sorry for my latest answer, I didn't read that its craps game.
from random import seed, randint
def simulate():
die1 = randint(1, 6)
die2 = randint(1, 6)
roll = die1 + die2
first_roll = roll
if first_roll == 7 or first_roll == 11:
return True
elif first_roll == 2 or first_roll == 3 or first_roll == 12:
return False
else:
while True:
second_roll = randint(1, 6) + randint(1, 6)
if second_roll == first_roll:
return True
elif second_roll == 7:
return False
# Main
def probability(n):
wins = 0
for i in range(n):
if simulate() == 1:
wins += 1
return wins
print(probability(100000))
I think its the answer, I changed the second part of simulate()
where its returning True, when second_roll == first_roll, returning False when second_roll==7, and repeats that while loop by continue, if second_roll is equal to other number.
Here is the game: the player throws a pair of standard, six-sided dice.
If the player rolls a total of 7 or 11, the player wins.
If the player rolls a total of 2, 3, or 12, the player loses.
For all other roll values, the player will repeatedly roll the pair of dice until either she rolls the initial value again (in which case they win) or 7 (bet is lost.)
Here is my code:
from random import seed, randint
def simulate():
win_count = 0
die1 = randint(1, 6)
die2 = randint(1, 6)
roll = die1 + die2
if roll == 7 or roll == 11:
return True
win_count += 1
elif roll == 2 or roll == 3 or roll == 12:
return False
else:
die1 = randint(1, 6)
die2 = randint(1, 6)
new_roll = die1 + die2
while roll != new_roll and roll != 7:
if new_roll == roll:
return True
win_count += 1
elif new_roll == 7:
return False
return win_count
## Main
for trials in range(1000):
simulate()
print(win_count / 1000)
I also need to find the probability of winning the "pass bet", which is what the rules are described above. The number of trials is 1000. However, nothing returns from this code. Where am I going wrong?
I'm new to programming and I have a task that I can't figure out on my own.
The task is to make a program that let's you decide how many dices to throw, 1 to 5, with checking if you make a wrong input.
After every roll the number of the die will show and the total so far.
If the die rolls a 6 then it is not included in the total and you get to more rolls. This is where I'm stuck. I want my program to restart the loop if the die turns a 6 and just ad 2 rolls to the sumDices and continue the loop, but I can't get it to work.
here is my code:
import random
numDices=0
total = 0
print("------------")
print("DICE ROLLING")
print("------------")
print()
exit=False
reset=False
while True:
while True:
numDices=int(input("How many dices to throw? (1-5) "))
if numDices<1 or numDices>5:
print("Wrong input, try again")
break
while True:
if reset==True:
break
for i in range(numDices):
dicesArray = list(range(numDices))
dicesArray[i] = random.randint(1, 6)
print(dicesArray[i])
total += dicesArray[i]
if dicesArray[i] == 1:
print("You rolled a one, the total is: ",str(total))
elif dicesArray[i] == 2:
print("You rolled a two, the total is: ",str(total))
elif dicesArray[i] == 3:
print("You rolled a three, the total is: ",str(total))
elif dicesArray[i] == 4:
print("You rolled a four, the total is: ",str(total))
elif dicesArray[i] == 5:
print("You rolled a five, the total is: ",str(total))
elif dicesArray[i] == 6:
total-=6
numDices+=2
print("You rolled a six, rolling two new dices")
reset=True
print("The total sum is",str(total),"with",numDices,"number of rolls.")
print()
restart=(input("Do you want to restart press Enter, to quit press 9. "))
if restart=="9":
exit=True
break
else:
print()
break
if exit==True:
break
You could do it the following way, slightly modifying your code, counting the available dices. I reduced the nested loops there too
import random
numDices=0
total = 0
print("------------")
print("DICE ROLLING")
print("------------")
print()
start = True
while start:
numDices=int(input("How many dices to throw? (1-5) "))
if numDices<1 or numDices>5:
print("Wrong input, try again")
break
total = 0
dices_counter = 0
while numDices > 0 :
eyes = random.randint(1, 6)
dices_counter+=1
total += eyes
if eyes == 1:
print("You rolled a one, the total is: ",str(total))
numDices-=1
elif eyes == 2:
print("You rolled a two, the total is: ",str(total))
numDices-=1
elif eyes == 3:
print("You rolled a three, the total is: ",str(total))
numDices-=1
elif eyes == 4:
print("You rolled a four, the total is: ",str(total))
numDices-=1
elif eyes == 5:
print("You rolled a five, the total is: ",str(total))
numDices-=1
elif eyes == 6:
total-=6
numDices+=2
print("You rolled a six, rolling two new dices")
print("The total sum is",str(total),"with",dices_counter,"number of rolls.")
print()
start=(input("Do you want to restart press Enter, to quit press 9. "))
if start=="9":
break
else:
print()
start = True
To solve your problem I would replace your current for loop with a while loop
Moreover, I see a lot of unacessary things in your code, I will try to list them :
Why do you use so many "while True"?
Why don't you just use exit() function to exit instead of using a
variable?
Is all the if part really necessary, can't you just print the
number?
Here's my proposal:
import random
remaining_dices=0
total = 0
print("------------")
print("DICE ROLLING")
print("------------")
print()
while True:
remaining_dices=int(input("How many dices to throw? (1-5) "))
if remaining_dices<1 or remaining_dices>5:
print("Wrong input, try again")
break
dicesArray = list()
while remaining_dices>0:
dice_value = random.randint(1, 6)
dicesArray.append(dice_value)
print(dice_value)
total += dice_value
remaining_dices -= 1
if(dice_value == 6):
total-=6
remaining_dices +=2
print("You rolled a 6, rolling two new dices")
else:
print("You rolled a " + str(dice_value) + ", the total is : " +str(total))
restart=(input("Do you want to restart press Enter, to quit press 9. "))
if restart=="9":
exit()
else:
print()
for i in range(numDices):
Your for loop limits the number of iterations as soon as range(numDices) is evaluated/executed. When you attempt to increase the number of iterations with numDices+=2 it does not have any effect because range(numDices) is only evaluated once.
If you want to be able to change the number of iterations, use another while loop and use i as a counter. Something like.
i = 0
while i <= numDices:
...
...
if ...:
...
elif ...:
...
i += 1
Then in the suite for elif dicesArray[i] == 6: the statement numDices += 2 will effectively increase the number of iterations.
I see another problem that you haven't mentioned. You start with a fixed length list based on the original value of numDices and you use i as an index for that list.
dicesArray = list(range(numDices))`
...
dicesArray[i]
...
If i can potentially be greater than the original numDices (greater than len(dicesArray)) you will eventually get an IndexError. You should probably start with an empty list and append to it. To get the most recent dice roll use dicesArray[-1] instead of dicesArray[i].
...
dicesArray = []
i = 0
while i <= numDices:
dicesArray.append(random.randint(1, 6))
total += dicesArray[-1]
if dicesArray[-1] == 1:
...
...
6.3.2. Subscriptions
Using a recursive function
import random
total = 0
diceRollList = []
# Define dice rolling function
def rollDice():
rollResult = random.randint(1, 6)
if rollResult == 6:
# If 6 Rolled run two more rolls and sum the results
print("Rolled a 6 Rolling 2 more")
return sum([rollDice() for _ in range(2)])
# If 6 not rolled return the result
print(f"Rolled a {rollResult}")
return rollResult
while True:
numberOfDice = int(input("How many Die to throw: "))
if numberOfDice not in range(1, 6):
print("Number of dice should be between 1 and 5")
break
for dice in range(numberOfDice):
print(f"Rolling Dice {dice}")
# Add result to the total
total += rollDice()
print(f"Running Total: {total}")
This one tracks how many it has rolled:
import random
a = int(0)
b = int(0)
c = int(0)
d = int(0)
e = int(0)
f = int(0)
limit = 101
count = 0
while True:
g = (random.randint(1, 6))
print(g)
count += 1
if g == 1:
a += 1
elif g == 2:
b += 1
elif g == 3:
c += 1
elif g == 4:
d += 1
elif g == 5:
e += 1
elif g == 6:
f += 1
if count > limit:
break
print(f"There are {a} 1's")
print(f"There are {b} 2's")
print(f"There are {c} 3's")
print(f"There are {d} 4's")
print(f"There are {e} 5's")
print(f"There are {f} 6's")
I am writing a lottery program, for my class. I have looked on stackoverflow for an answer but all I have found have been to advanced. I was wondering if there is a way to shorten the if statements and have fewer of them.
import random
def lottery():
lottoNumber1 = random.randint(1,50)
print(lottoNumber1)
lottoNumber2 = random.randint(1,50)
print(lottoNumber2)
lottoNumber3 = random.randint(1,50)
print(lottoNumber3)
return lottoNumber1,lottoNumber2,lottoNumber3
userChoice1 = int(input('Choose a number between 1 and 50: '))
userChoice2 = int(input('Choose a number between 1 and 50: '))
userChoice3 = int(input('Choose a number between 1 and 50: '))
lottoNumber1, lottoNumber2, lottoNumber3 = lottery()
if userChoice1 == lottoNumber1:
if userChoice1 == lottoNumber2:
if userChoice1 == lottoNumber3:
if userChoice2 == lottoNumber1:
if userChoice2 == lottoNumber2:
if userChoice2 == lottoNumber3:
if userChoice3 == lottoNumber1:
if userChoice3 == lottoNumber2:
if userChoice3 == lottoNumber3:
print('You win $1,000')
else:
print('Try it again!')
main()
If you create two sets, one holding the lottery numbers and the other holding the user choices then one if statement could compare them:
import random
# Use sets to ensure lottery numbers and user choices are unique
lottoNumbers = set()
userChoices = set()
while len(lottoNumbers) < 3:
lottoNumbers.add(random.randint(1,50))
while len(userChoices) < 3:
userChoices.add(input('Choose a number between 1 and 50: '))
print(lottoNumbers)
print(userChoices)
if lottoNumbers == userChoices:
print('You win $1,000')
This will work for you.
from random import randint
def lottery():
return [randint(1, 50) for x in range(3)]
user_choices = list(map(int, [input('Choose a number between 1 and 50: ') for x in range(3)]))
lotto_numbers = lottery()
print(user_choices)
print(lotto_numbers)
if any(user_choice == lotto_number for user_choice, lotto_number in zip(sorted(user_choices), sorted(lotto_numbers)))
I'm a beginner, and I wanted to know if there was a simpler way of write this out in Python. I'm assuming some type of dictionary, but I do not understand how to write it out.
I was on a cruise a couple of days ago, and I play craps. I wanted to know if the odds are somewhat correct. So, I wrote this, but I know there is a simpler way.
import random
dice2 = 0
dice3 = 0
dice4 = 0
dice5 = 0
dice6 = 0
dice7 = 0
dice8 = 0
dice9 = 0
dice10 = 0
dice11 = 0
dice12 = 0
for i in range(100000):
dice1 = random.randint(1,6)
dice2 = random.randint(1,6)
number = dice1 + dice2
#print(dice1)
if number == 2:
dice2 +=1
elif number == 3:
dice3 += 1
elif number == 4:
dice4 += 1
elif number == 5:
dice5 += 1
elif number == 6:
dice6 += 1
elif number == 7:
dice7 += 1
elif number == 8:
dice8 += 1
elif number == 9:
dice9 += 1
elif number == 10:
dice10 += 1
elif number == 11:
dice11 += 1
elif number == 12:
dice12 += 1
total = dice2+dice3+dice4+dice5+dice6+dice7+dice8+dice9+dice10+dice11+dice12
At the end of this, it just prints out the percentage of hits on numbers from 2-12.
I'd use Counter, as that's what it was made for:
from random import randint
from collections import Counter
counts = Counter(randint(1, 6) + randint(1, 6) for i in range(100000))
total = sum(counts.values())
number_of_tens = counts[10]
from random import randint
dice = [0]*11
for i in range(100000):
dice[randint(1,6)+randint(1,6)-2] += 1
total = sum(dice) #it is 100000, of course
for i, v in enumerate(dice, 2):
print('{0}: {1}%'.format(i, v*100.0/total))
import random
def roll(n=6):
return random.randint(1, n)
dice = dict.fromkeys(range(2, 13), 0)
for i in range(100000):
number = roll() + roll()
dice[number] += 1
total = float(sum(dice.values()))
for k,v in dice.items():
print "{}, {:.2%}".format(k, v/total)