Trouble correctly adding numbers in a python program - python

I am trying to simulate dice being rolled. Die_1 + Die_2 five times. The program runs, but the math is wrong. I have tried this multiple ways, but cannot get the math correct. The die are only being rolled one at a time, so a 1 and a six are possibilities. It must be an overly tired oversight. Any ideas would be fantastic. Code and output below. Thank you to anyone who can help.
# This program will simulate dice rolls 5 different
# times and add the total of each roll.
import random
import math
MIN = 1
MAX = 6
ROLLS = 5
def main():
for count in range(ROLLS):
die_1 = (random.randint(MIN, MAX))
die_2 = (random.randint(MIN, MAX))
combined_roll = point(die_1, die_2)
print('Here are the combined rolls for the dice!')
print(random.randint(MIN, MAX))
print(random.randint(MIN, MAX))
print('The combined roll is:', combined_roll)
def point(die_1, die_2):
roll_1 = die_1 + die_2
combined_roll = roll_1
return combined_roll
main()
Here are the combined rolls for the dice!
4
3
The combined roll is: 4
Here are the combined rolls for the dice!
2
2
The combined roll is: 7
Here are the combined rolls for the dice!
5
4
The combined roll is: 5
Here are the combined rolls for the dice!
3
5
The combined roll is: 9
Here are the combined rolls for the dice!
3
1
The combined roll is: 11

The math and everything is correct. It is indeed a symptom of being tired.
You're printing out entirely new numbers in these 2 lines:
print(random.randint(MIN, MAX))
print(random.randint(MIN, MAX))
Compared to what your die rolls actually were, earlier in time.
die_1 = (random.randint(MIN, MAX))
die_2 = (random.randint(MIN, MAX))
Time has passed so your random number generation is going to be in a different state.
So change the prints to:
print(die_1)
print(die_2)

This is best achieved with a simple function and random.randint:
>>> from random import randint
>>> def roll_dice(n=1):
... return [randint(1, 6) for _ in range(n)]
...
1-die roll:
>>> roll_dice()
[2]
>>> roll_dice()
[2]
>>> roll_dice()
[5]
2-die roll:
>>> roll_dice(2)
[6, 2]
>>> roll_dice(2)
[6, 2]
>>> roll_dice(2)
[5, 5]
>>>
You can easily sum a 2-die roll by:
>>> sum(roll_dice(2))
6
>>> sum(roll_dice(2))
7
>>> sum(roll_dice(2))
8

The second set if print statements mean to print die_1 and die_2, nit calls to random again. If you call random again, you get new random numbers.

Related

Dice throwing simulator

I am making a dice throwing simulator that generates N rolls for me, but assigns a name to each roll, for example:
[5,7,8]
then print
Player 1: 5
Player 2: 7
Player 3: 8
this is my code:
import random
players = int(input("Number of players:"))
throw_i = [random.randint(1, (30 * 1)) for _ in range(players)]
print(throw_i)
#Print results
for i in range (1, players+1):
print('Player', i,':', throw_i[0]+1)
An example output of my code is:
[22, 13, 18, 13]
Player 1 : 23
Player 2: 23
Player 3 : 23
Player 4 : 23
It does not work!
The last two lines are the problem.
for i in range (1, players+1):
print('Player', i,':', throw_i[0]+1)
This reads:
For every number between 1 and (players+1), print out some text followed by the first throw, plus one
That throw_i[0] always refers to the very first number generated. Maybe you mean to do throw_i[i], which will be off-by-one since lists start with zero and you're starting with 1, so throw_i[i-1]?
Replace
print('Player', i,':', throw_i[0]+1)
with
print('Player', i,':', throw_i[i-1])
You are using 30 as max range of randint but a dice has 6.
import random
players = int(input("Number of players:"))
throw_i = [random.randint(1, 6) for _ in range(players)] # As far as i know a dice has numbers from 1 to 6.
print(throw_i)
#Print results
for i in range (0, players):
print('Player', i+1,':', throw_i[i])
Input: Number of players:4
Output:
[4, 5, 6, 4]
Player 1 : 4
Player 2 : 5
Player 3 : 6
Player 4 : 4
EDIT: As pointed out by #Adam that die can be of other sides as well. Then you should just change:
for i in range (0, players):
print('Player', i+1,':', throw_i[i])

How to calculate the average of the sum of 10 random rolled dices

The program gonna rolls 10 fair dice (six sided) until the sum of these rolls is prime and larger or equal to 45 and then output the average of the sum of all these rolls. I am trying to use a while loop. Here is what I have until now:
import random
# function to generate a random number between 1 and 6
def rollDice():
roll = random.randint(1,6)
return roll
for i in range(10):
print(rollDice(), end = ' ')
# checks if the sum of the dices value is prime
def is_prime(dices):
total_sum = sum(dices)
for x in range(2,int(total_sum**0.5)+1):
if total_sum % x == 0:
return False
return True
total_sum = 0
isPrime = False
while isPrime is False or total_sum < 45:
dices = [rollDice() for dice in range(10)]
total_sum = sum(dices)
isPrime = is_prime(dices)
print('Average of the sum of the ten-rolls is {0:.2f}'.format(float(total_sum)/10))
The problem is sometimes I run the program the sum of those 10 rolls is not larger than 45, and the Average of those sums are somehow always equal 4.70 no matter what
The output supposed to be: display 10 random numbers from 1-6 Average of the sum of the ten-rolls is ...
The dice rolls your are printing is simply not the one that you have at the end of the loop. Delete the lines with print(rollDice()).
You'd better print the roll at the end of the code if your really want to see it.
About the average being always 4.7 it is simply because you don't have much choice of prime numbers between 45 and 60 (your maximum with 10 dices). It can be 47, 53, 59.
I didn't do the maths now, but it's pretty clear that 59 is the least probable of the combination (you have just 1 combination possible, that is 9 times 6 + 1 time 5, so probability is (1/6)^10), while 47 appears to be the most probable outcome.

dice roll simulation in python

I am writing a program that is to repeatedly roll two dice until the user input target value is reached. I can not figure out how to make the dice roll happen repeatedly. Please, help...
from random import randrange
print ("This program rolls two 6-sided dice until their sum is a given target value.")
input = int (input("Enter the target sum to roll for:"))
#def main():
dice1 = randrange (1,7)
dice2 = randrange (1,7)
sumofRoll = dice1 + dice2
output = "Roll: {} and {}, sum is {}".format (dice1,dice2,sumofRoll)
print (output)
if sumofRoll == input:
print ("All done!!")
if sumofRoll != input:
#how do I make this repeatedly run until input number is reached?!
Here is a complete working code which takes care of invalid sum entered as input as well. The sum of two dice rolls cannot be either less than 2 or more than 13. So a check for this condition makes your code slightly more robust. You need to initialize sumofRoll = 0 before entering the while loop as this would be needed to first enter the while loop. The value of 0 is a safe value because we excluded the value of 0 entered by user to be a valid sum.
from random import randrange
print ("This program rolls two 6-sided dice until their sum is a given target value.")
input_sum = int(input("Enter the target sum to roll for:"))
def main():
sumofRoll = 0
if input_sum < 2 or input_sum > 13:
print ("Enter a valid sum of dices")
return
while sumofRoll != input_sum:
dice1 = randrange (1,7)
dice2 = randrange (1,7)
sumofRoll = dice1 + dice2
output = "Roll: {} and {}, sum is {}".format (dice1,dice2,sumofRoll)
print (output)
if sumofRoll == input_sum:
print ("All done!!")
main()
This program rolls two 6-sided dice until their sum is a given target value.
Enter the target sum to roll for:10
Roll: 3 and 5, sum is 8
Roll: 6 and 6, sum is 12
Roll: 5 and 1, sum is 6
Roll: 2 and 5, sum is 7
Roll: 6 and 6, sum is 12
Roll: 3 and 5, sum is 8
Roll: 1 and 2, sum is 3
Roll: 6 and 4, sum is 10
All done!!
I took your game and added some elements for you to peek through. One is you could use random.choice and select from a die list instead of generating new random ints repeatedly. Second you can use a try/except block to only accept an int and one that is within the range of (2, 13). Next we can add a roll_count to track the amount of rolls to hit our target. Our while loop will continue until target == roll_sum and then we can print our results.
from random import choice
die = [1, 2, 3, 4, 5, 6]
print('This program rolls two 6-sided dice until their sum is a given target.')
target = 0
while target not in range(2, 13):
try:
target = int(input('Enter the target sum to roll (2- 12): '))
except ValueError:
print('Please enter a target between 2 and 12')
roll_sum = 0
roll_count = 0
while target != roll_sum:
die_1 = choice(die)
die_2 = choice(die)
roll_sum = die_1 + die_2
roll_count += 1
print('You rolled a total of {}'.format(roll_sum))
print('You hit your target {} in {} rolls'.format(target, roll_count))
...
You rolled a total of 4
You rolled a total of 12
You hit your target 12 in 29 rolls
This is a simple while loop:
sumofRoll = -1; #a starting value!
while sumofRoll != input:
#Put the code that updates the sumofRoll variable here
count = 0
while(sumOfRoll != input):
dice1 = randrange(1,7)
dice2 = rangrange(1,7)
count = count + 1
sumOfRoll = dice1 + dice2
print("sum = %s, took %s tries" % (sumOfRoll, count))
Use a do while statement
do:
dice1=randrange(1,7)
...
while(sumofroll != input)
print("all done")

Counting/random int in while loop

I want this while loop to change numbers with every iteration (both the count and random int.) but when I run the program, the loop just goes on with the same numbers on the count and random int.:
# if 4 sides
die1 = random.randint(1,4)
die2 = random.randint(1,4)
count = 1
while sides == 4 and die1 != die2:
print (count, ". die number 1 is", die1, "and die number 2 is", die2,".")
count == count + 1
print ("You got snake eyes! Finally! On try number", count,".")
Each time you call random.randint(1,4), you are creating a single random number. It does not magically change to a new random number whenever you print it.
Generate new random numbers with random.randint(1, 4) inside your while loop.
The second problem is that count == count + 1 checks for equality (and returns False in your case). To do an assignment, use the assignment operator = or count += 1 to increment count by one.
If you want a generator that endlessly spits out random numbers, write one:
>>> import random
>>> def rng(i, j):
... while True:
... yield random.randint(i, j)
...
>>> random_gen = rng(1, 4)
>>> next(random_gen)
2
>>> next(random_gen)
3
>>> next(random_gen)
2
>>> next(random_gen)
2
>>> next(random_gen)
1
You need to do the random calls also inside the while loop otherwise they will not change. And the other thing is that you compare == and not set = the counter:
import random
sides = 4
count = 1
die1 = random.randint(1,4)
die2 = random.randint(1,4)
while sides == 4 and die1 != die2:
print (count, ". die number 1 is", die1, "and die number 2 is", die2,".")
count += 1
die1 = random.randint(1,4)
die2 = random.randint(1,4)
print ("You got snake eyes! Finally! On try number", count,".")
Trying a test run gives me:
1 . die number 1 is 4 and die number 2 is 3 .
2 . die number 1 is 2 and die number 2 is 1 .
3 . die number 1 is 1 and die number 2 is 2 .
4 . die number 1 is 3 and die number 2 is 4 .
5 . die number 1 is 1 and die number 2 is 4 .
You got snake eyes! Finally! On try number 6 .
One alternative that is almost identical but uses break instead of conditions on the while loop would be:
import random
sides = 4
count = 1
def tossdie():
"""Function to create a random integer for a die"""
return random.randint(1,4)
while True:
die1 = tossdie()
die2 = tossdie()
print (count, ". die number 1 is", die1, "and die number 2 is", die2,".")
if die1 == die2:
break
count += 1
print ("You got snake eyes! Finally! On try number", count,".")
Not sure why you needed the sides variable, so I left it out.
You want to roll the die in every loop, which means you have to re-assign die1 and die2 to a random number in each loop.
import random
# Initial parameters
die1 = random.randint(1,4)
die2 = random.randint(1,4)
count = 1
# Loop and roll die each time
while die1 != die2:
print(count, ". die number 1 is", die1, "and die number 2 is", die2,".")
die1 = random.randint(1,4)
die2 = random.randint(1,4)
count += 1
# Print on which die roll you got two equal die numbers rolled
print ("You got snake eyes! Finally! On try number", count,".")
You can use a for loop with iter to spit out pairs of random numbers , enumerate will do the counting, for snake-eyes you should also be checking that both are 1's not a random matching pair:
from random import randint
def repeating_rand(i, j):
for count, (r1, r2 ) in enumerate(iter(lambda: (randint(i, j), randint(i, j)), None), 1):
if r1 == 1 and r2 == 1:
return "You got snake eyes! Finally! On try number {}.".format(count)
print("Try no. {}, die number 1 is {} and die number 2 is {}".format(count, r1, r2))
Output:
In [12]: repeating_rand(1, 4)
Try no. 1, die number 1 is 1 and die number 2 is 2
Try no. 2, die number 1 is 4 and die number 2 is 1
Try no. 3, die number 1 is 1 and die number 2 is 2
Try no. 4, die number 1 is 1 and die number 2 is 3
Try no. 5, die number 1 is 1 and die number 2 is 3
Try no. 6, die number 1 is 3 and die number 2 is 4
Try no. 7, die number 1 is 4 and die number 2 is 2
Try no. 8, die number 1 is 1 and die number 2 is 2
Try no. 9, die number 1 is 3 and die number 2 is 2
Try no. 10, die number 1 is 4 and die number 2 is 3
Try no. 11, die number 1 is 1 and die number 2 is 3
Try no. 12, die number 1 is 3 and die number 2 is 4
Out[12]: 'You got snake eyes! Finally! On try number 13.'

Dice counter error

Im making a program in python 2.7 that are going to roll dices, and then count how many times each number gets rolled. But cant seem to figure out this problem.
it returns: Traceback (most recent call last):
File "DiceRoller.py", line 16, in
counter[s] += 1
KeyError: 3
from random import randint
while True:
z = raw_input("How many sides should the dice(s) have?\n> ")
i = 0
x = raw_input("How many dices do you want?\n> ")
dice = {}
while i <= int(x):
dice[i] = randint(1,int(z))
i += 1
counter = {}
for p, s in dice.iteritems():
counter[s] += 1
print counter
raw_input("Return to restart.")
You are setting each counter to the value +1:
counter[s] =+ 1
# ^^^
You are not using += there; Python sees that as:
counter[s] = (+1)
Swap the + and the =:
counter[s] += 1
This will raise an exception as the key s is not going to be present the first time; use counter.get() to get a default value in that case:
counter[s] = counter.get(s, 0) + 1
or use a collections.defaultdict() object rather than a regular dictionary:
from collections import defaultdict
counter = defaultdict(int)
for s in dice.itervalues():
counter[s] =+ 1
or use a collections.Counter() object to do the counting:
from collections import Counter
counter = Counter(dice.itervalues())
Use xrange and just increment each count as you go, using two dicts is unnecessary if you just want to count how many times each side is rolled:
from collections import defaultdict
from random import randint
z = int(raw_input("How many sides should the dice(s) have?\n> "))
x = int(raw_input("How many dices do you want?\n> "))
counts = defaultdict(int) # store dices sides as keys, counts as values
# loop in range of how many dice
for _ in xrange(x):
counts[randint(1,z)] += 1
for side,count in counts.iteritems():
print("{} was rolled {} time(s)".format(side,count))
Output:
How many sides should the dice(s) have?
> 6
How many dices do you want?
> 10
1 was rolled 2 time(s)
2 was rolled 3 time(s)
3 was rolled 1 time(s)
4 was rolled 1 time(s)
5 was rolled 1 time(s)
6 was rolled 2 time(s)
If you want to include all dice sides in the output you can create the counts dict using xrange:
counts = {k:0 for k in xrange(1, z+1)}
So the output will then be:
How many sides should the dice(s) have?
> 6
How many dices do you want?
> 10
1 was rolled 0 time(s)
2 was rolled 2 time(s)
3 was rolled 0 time(s)
4 was rolled 0 time(s)
5 was rolled 5 time(s)
6 was rolled 3 time(s)

Categories