Calculating an average of multiple random numbers Python - python

I am fairly new to Python and have run into a roadblock with trying to calculate an average of a bunch of random numbers.The general overview of the program is that it is a die rolling program which prompts the user to enter a certain amount of sides and it then rolls until the program outputs snake eyes. It also keeps track of the amount of doubles rolled and how long it took to get snake eyes. Then create an average of the numbers that were rolled for each die throughout the program. This is where I am lost.
EDIT: I deleted my original code and worked in Vasilis's answer:
import random
while True:
#prompts user for valid number
user_s = int (input ("How many sides on your dice? "))
if user_s < 3:
print("That is not a valid size value, please enter a positive number")
if user_s >= 3:
break
print()
print("Thanks! Here we go...")
print()
double_count = 0
roll_count = 0
sum1 = 0 # Used to calculate sum of die_1
sum2 = 0 # Used to calculate sum of die_2
while True:
roll_count += 1
die_1 = random.randint(1,user_s)
die_2 = random.randint (1,user_s)
print(roll_count,".", " Die number 1 is ", die_1 , " and die number 2 is ", die_2, ".", sep ="")
if die_1 == die_2:
double_count += 1
if die_1 == 1 and die_2 == 1:
break
# Making sum
sum1 = sum1 + die_1
sum2 = sum2 + die_2
print("You finally got snake eyes on try number", roll_count)
print("Along the way you rolled a double", double_count,"times")
print(die_1)
print(die_2)
# Integer divisions
avg_roll1 = sum1 // roll_count
avg_roll2 = sum2 // roll_count
print("The average roll for die 1 was", format(avg_roll1,".2f"))
print("The average roll for die 2 was", avg_roll2)
However like he pointed out it doesn't take all of the numbers that is recorded through all the rolls, rather the last number.
Any help to accomplish that would be appreciated.
Thanks!

I made a few changes in your code if you like to take a look. I assumed that you wanted the average to be calculated as an integer although you can change that. You use die_1 and die_2 as simple integer variables and thus they hold only the last value generated by random.randint(1,user_s):
import random
'''Skipped input part'''
print()
print("Thanks! Here we go...")
print()
double_count = 0
roll_count = 0
sum1 = 0 # Used to calculate sum of die_1
sum2 = 0 # Used to calculate sum of die_2
while True:
roll_count += 1
die_1 = random.randint(1,user_s)
die_2 = random.randint (1,user_s)
print("DIE_1: ", die_1)
print("DIE_2: ", die_2)
print(roll_count,".", " Die number 1 is ", die_1 , " and die number 2 is ", die_2, ".", sep ="")
if die_1 == die_2:
double_count += 1
if die_1 == 1 and die_2 == 1:
break
# Making sum
sum1 = sum1 + die_1
sum2 = sum2 + die_2
print("You finally got snake eyes on try number", roll_count)
print("Along the way you rolled a double", double_count,"times")
print(die_1)
print(die_2)
# Integer divisions
avg_roll1 = sum1 // roll_count
avg_roll2 = sum2 // roll_count
print("The average roll for die 1 was", avg_roll1)
print("The average roll for die 2 was", avg_roll2)

Got it myself.
Set the accumulator variable = to the die rolls. In this case sum1 and sum2 are the variables.
# make all of the functions in the "random" module available to this program
import random
while True:
#prompts user for valid number
user_s = int (input ("How many sides on your dice? "))
if user_s < 3:
print("That is not a valid size value, please enter a positive number")
if user_s >= 3:
break
print()
print("Thanks! Here we go...")
print()
double_count = 0
roll_count = 0
sum1 = 0 # Used to calculate sum of die_1
sum2 = 0 # Used to calculate sum of die_2
#while statement for die rolls
while True:
roll_count += 1
die_1 = random.randint(1,user_s)
sum1 += die_1
die_2 = random.randint (1,user_s)
sum2 += die_2
print(roll_count,".", " Die number 1 is ", die_1 , " and die number 2 is ", die_2, ".", sep ="")
if die_1 == die_2:
double_count += 1
if die_1 == 1 and die_2 == 1:
break
print("You finally got snake eyes on try number", roll_count)
print("Along the way you rolled a double", double_count,"times")
# Integer divisions
avg_roll1 = sum1 / roll_count
avg_roll2 = sum2 / roll_count
print("The average roll for die 1 was", format(avg_roll1,".2f"))
print("The average roll for die 2 was", format(avg_roll2,".2f"))

Related

Program that separately adds positive and negative inputs and displays the two sums

I'm trying to solve this hw problem:
Write a program that allows a user to keep inputting numbers until the number zero is entered. The program should keep track of two separate sums: The sum of all positive numbers entered and the sum of all negative numbers entered. Once the loop ends the program should display the two sums.
This is what I have so far:
number = int(input("Please enter a number, press 0 to end"))
sum1 = 0
sum2 = 0
while number != 0:
number = int(input("Please enter a number, press 0 to end"))
if number > 0:
sum1 += number
else:
sum2 += number
print("positive sum is", sum1)
print("negative sum is", sum2)
the problem i'm facing is that number needs to be defined in order to start the while loop, and then for the loop to keep asking the question, i need to define number inside the loop too and that messes up the count because the first user input is used just to start the loop and is not counted.
How do i fix this?
You can simply initialize number to something other than 0, so the number isn't asked twice at the start of the program.
sum1 = 0
sum2 = 0
number = -1
while number != 0:
number = int(input("Please enter a number, press 0 to end"))
if number > 0:
sum1 += number
else:
sum2 += number
print("positive sum is", sum1)
print("negative sum is", sum2)
Try doing this. You can delete the sample_input lines and uncomment your original line taking input from stdin:
sample_input = iter([3, -3, 2, -2, 1, -10, 0])
sum1 = 0
sum2 = 0
number = 999
while number != 0:
number = next(sample_input)
#number = int(input("Please enter a number, press 0 to end"))
if number > 0:
sum1 += number
else:
sum2 += number
print("positive sum is", sum1)
print("negative sum is", sum2)
Sample output:
positive sum is 6
negative sum is -15
Use the walrus:
sum1 = 0
sum2 = 0
while number := int(input("Please enter a number, press 0 to end")):
if number > 0:
sum1 += number
else:
sum2 += number
print("positive sum is", sum1)
print("negative sum is", sum2)
And I'd suggest sum_pos and sum_neg as better more meaningful variable names.
Don't use the number test in the while condition. Check for it being 0 after getting the input and break out of the loop.
while True:
number = int(input("Please enter a number, press 0 to end"))
if number == 0:
break
elif number > 0:
sum1 += number
else:
sum2 += number
I prefer this style because it doesn't require you to initialize the variable to a special value. Also, it allows the end value to be something that wouldn't be useful in the rest of the computation.

How do I limit it to 5 attempts and how they get 10 points added to their score if they guess correct, and they lose 1 point for wrong guess?

Problem: (Python) Write a program that asks the user to guess a random number between 1 and 10. If they guess right, they get 10 points added to their score, and they lose 1 point for an incorrect guess. Give the user five numbers to guess and print their score after all the guessing is done.
fs: I already have this code below, my problem now is how do I limit it to 5 attempts, also how to add "score system" like they get 10 points added to their score if they guess right, and they lose 1 point for an incorrect guess.
My code:
import random
target_num, guess_num = random.randint(1, 10), 0
while target_num != guess_num:
guess_num = int(input('Guess a number between 1 and 10 until you get it right : '))
print('Well guessed!')
Use attempt variable to track how many times the user has guessed.
Use score variable to track the accumulated score from guessing.
import random
target_num, guess_num = random.randint(1, 10), 0
attempt = 0
score = 0
while attempt < 5:
attempt += 1
guess_num = int(input('Guess a number between 1 and 10: '))
if target_num == guess_num:
score += 10
print('Correct! You get +10 points')
else:
score -= 1
print('Wrong! You get -1 point')
print("Your score: ", score, " points.")
You should do it like this -
import random
target_num, guess_num, tries, score= random.randint(1, 10), 0, 5, 0
for i in range(tries):
guess_num = int(input('Guess a number between 1 and 10 until you get it right : '))
if guess_num == target_num:
print('Well guessed!')
score+=10
else:
score-=1
print(f'Your final score is {score}')

Python Dice Roller - How can I total all dice?

I want to get the total amount of the dice results:
import random
min = 1
max = 6
numDices = 0
roll_again = "yes"
sum = 0
while roll_again == "yes" or roll_again == "y":
numDices = int(raw_input("how many dices "))
for i in range(numDices):
dicesArray = list(range(numDices))
dicesArray[i] = random.randint(min, max)
print(dicesArray[i])
sum += dicesArray[i]
print("sum ", sum)
roll_again = raw_input("Roll the dices again? ")
but I get this when I run the code:
how many dices 3
4
('sum ', 4)
2
('sum ', 6)
6
('sum ', 12)
Roll the dices again?
Also, how can I limit the user to roll 1 to 5 dice max?
Thank you so much Python experts!
You should change the indentation of the print("sum") statement so you only print the final sum. Also add a check for the dice number like below.
import random
min = 1
max = 6
numDices = 0
roll_again = "yes"
# Greeting here
print("Welcome to the dice rolling program!")
raw_input("Press any key to continue...")
while roll_again == "yes" or roll_again == "y":
sum = 0 # sum should be inside while loop
numDices = int(raw_input("How many dice? "))
if (numDices < 1 or numDices > 5):
print("Allowed number of dice is 1 - 5. Please choose again.")
continue
for i in range(numDices):
dicesArray = list(range(numDices))
dicesArray[i] = random.randint(min, max)
print(dicesArray[i])
sum += dicesArray[i]
print("sum: " + str(sum))
roll_again = raw_input("Roll the dice again? ")
You need to check and make sure that numDices stays between 1 and 6. You can do that by adding an if condition before entering the for loop.
import random
min = 1
max = 6
numDices = 0
roll_again = "yes"
sum = 0
while roll_again == "yes" or roll_again == "y":
numDices = int(raw_input("how many dices "))
if numDices < 1 or numDices > 6:
print ("Invalid range. You can roll only between 1 and 5 times.")
continue
for i in range(numDices):
dicesArray = list(range(numDices))
dicesArray[i] = random.randint(min, max)
print(dicesArray[i])
sum += dicesArray[i]
print("sum ", sum)
roll_again = raw_input("Roll the dices again? ")

Python - checking a list for possible patterns and if the list meets a specific condition

I'm a novice making a small game for learning purposes.
The game rolls dice based on the inputs of the user.
The part I'm having trouble with is I want to check for patterns in the list "rolls"
patterns include:
all dice are the same value and the # of sides >=4 EXAMPLE [1, 1, 1, 1] < values are the same, atleast 4 sides. If true then mutiply user_Score by 10
at least half of the dice are >= "average_sum" with the condition that the list must have >= 5 dice
EXAMPLE if avg_sum = 2 and rolls = [2,3,4,1,1,] If true then mutiply user_Score by 5
all of the dice are different values with the conditions # of dice > 4 and # of sides > # of dice
[10, 11, 12, 13, 14]
No pattern matches. -> Multiply user_Score by 1
number_dice = int( input( "How many dice are you using? Must be between 3-6 inclusive" ) )
faces = int( input( "how many sides are on your die? enter a number between 2-20 inclusive: "))
# Set range for number of dice
#generate a random number between 1 and faces
#Add dice_roll to the list
rolls = []
for die in range(number_dice):
dice_roll = random.randint(1, faces)
rolls.append(dice_roll)
#print the score from each dice rolled
print("You have rolled: " + str(rolls))
#calculate sum of score
sum = sum(rolls)
#calculate the average and round to the nearest integer
average_sum = round(sum / number_dice)
print("These die sum to: " + str(sum) + " and have an average value of: " + str(average_sum))
#Calculate the max possible score
max_score = (number_dice * faces)
#calculate the users score
user_score = float( sum / max_score )
print("your max possible score is " + str(max_score))
print("your score is " + str(user_score))
#-----------------------------------------------------------------------------------
#now calculate the bonus factor
#Check if the list "rolls" contains the same value for each index
if rolls == {repeatingvalues???} and rolls {number_dice>=4}:
user_Score * 10
elif rolls == {half of dice > average} and {number_dice >=5}:
user_Score * 5
elif rolls == {all dice have different values} and { number_dice > 4}{faces> number_dice}:
user_score * 8
else:
user_score * 1
Not sure how to make this statement search the list for a pattern^^^^^^
Define a function to check for a repeating pattern that returns True or False
def has_repeats(my_list):
first = my_list[0]
for item in mylist:
if not item == first:
return False
return True
And then define a function to check for a no duplicates that returns True or False
def all_different(my_list):
# Remove duplicates from list
my_list2 = list(dict.fromkeys(my_list))
return len(my_list) == len(my_list2)
And finally define a function to check if half the dice are greater than the average:
def half_greater_than_averge(my_list, average):
a = 0
b = 0
for item in my_list:
if item > average:
a += 1
else:
b += 1
return a > b
So you final checks will be:
if has_repeats(rolls) and number_dice >= 4:
user_Score * 10
elif half_greater_than_averge(rolls, average_sum) and number_dice >= 5:
user_Score * 5
elif all_different(rolls) and number_dice > 4 and faces > number_dice:
user_score * 8
else:
user_score * 1
Check out my solution where add # ------ SOLUTION STARTS HERE -------
I helped refactor your code too. You shouldn't be using sum as a variable name (or identifier) in your code cos it's a reserved python keyword. So I changed it to my_sum. Check if it still works as desired.
import math # import math at the top
import random
number_dice = int( input( "How many dice are you using? Must be between 3-6 inclusive" ) )
faces = int( input( "how many sides are on your die? enter a number between 2-20 inclusive: "))
# Set range for number of dice
#generate a random number between 1 and faces
#Add dice_roll to the list
for die in range(number_dice):
dice_roll = random.randint(1, faces)
rolls.append(dice_roll)
#print the score from each dice rolled
print("You have rolled: " + str(rolls))
#calculate sum of score
my_sum = sum(rolls)
#calculate the average and round to the nearest integer
average_sum = round(my_sum / number_dice)
print("These die sum to: " + str(my_sum) + " and have an average value of: " + str(average_sum))
#Calculate the max possible score
max_score = (number_dice * faces)
#calculate the users score
user_score = float( my_sum / max_score )
print("your max possible score is " + str(max_score))
# ------ SOLUTION STARTS HERE------
rolls.sort()
rolls.reverse()
for item in rolls:
if (rolls.count(item) >= 4) and (number_dice >= 4):
user_score *= 10
break
elif (rolls[math.ceil(len(rolls)/2) -1] >= average_sum ) and (number_dice >= 5):
user_score *= 5
break
elif (sorted(rolls)==sorted(list(set(rolls))))and (number_dice > 4) and (faces > number_dice):
user_score *= 8
break
else:
user_score *= 1
# ------ SOLUTION ENDS HERE------
print("your score is " + str(user_score))
Here is a simple, faster and more 'Pythonic' way of doing it.
if all(x == rolls[0] for x in rolls):
print("Same")
elif len(rolls) == len(set(rolls)):
print("Unique")
elif number_dice/2 <= [x > avg_sum for x in rolls].count(True):
print("Half")
else:
print("No match")
The 'and' conditions are missing. Please feel free to add them.
Bonus
from random import randint
faces = int(input('Number of faces:'))
number_dice = int(input('Number of dice:'))
rolls = [randint(1, faces) for _ in range(number_dice)]
Feel free to explore

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

Categories