Dice game (simulating many throws with 3 dices) - python

I am trying to code a dice game:
How do I write a function that is supposed to simulate 1000 throws of 3 dice and print the number of times a throw resulted in exactly 2 of the dice, but not all 3, landing on the same number. Meaning not (1,2,3) or (5,5,5), but like this (1,2,2).
def throw():
I know I need to use the random- library to generate numbers between 1 and 6.
What I need is example code on how I can approach this and what to do.

Use a for loop and list comprehension to generate the throw:
for i in range(1000):
throw = [random.randint(1, 6) for x in range(3)]
Then just write code to check your condition, something like:
valid = any([throw.count(i) == 2 for i in range(1, 6)])
Then if it's valid is True you can do with it what you need.

The function could be something like this:
import random
matches = 0
for i in range(1000): # 1000 throws
result = (random.randint(1,6), random.randint(1,6), random.randint(1,6)) # three dices randomly from 1 to 6 in a tuple (list)
for i in range(1,7): # count from 1 to 6
if result.count(i) == 2:
matches += 1
break # breaking out of this for-loop for performance improvement
print("Got "+str(matches)+" matches.")
Of course, this code could be heavily improved. But according to your question I assume that you are quite new to Python programming. This is why I tried to write a code that is self-explanatory.
Meta: please keep in mind that Stack Overflow is not the right place to ask for specific coding. It's intended to be a place where you provide code which contains error that you are unable to fix.

Related

is there a faster way to receive input with python? (USACO)

I'm new to competitive coding and was doing a practice USACO question with an input structure like this:
5 3
1
6
4
3
1
the first number is the number of numbers below it, and the second number next to it would be needed for something else in the problem
heres the code I wrote to try to recieve the input
a = list(input())
n = int(a[0])
k = int(a[2])
diamonds = []
for x in range(n):
this = int(input())
diamonds.append(this)
the first two numbers I put in a list, converted to int, then assigned them to two variables, I then created an array with a for loop to receive the list of numbers below, converting them to int first
although it works, I feel like this is inefficent and is wasting time, is there another, faster way of doing this?

Python input multiple lines and spaces

Im trying to solve one of the a2oj problems "given three numbers a , b and c. print the total sum of the three numbers added to itself."
I came with this
import sys
numbers = [int(x) for x in sys.stdin.read().split()]
print(numbers[0] + numbers[1] + numbers[2])
I saw many topics but I cant figure out how to read just 3 values from input. I know I can stop this procces by typing CTRL+D, but is there any possibility to make it automatic (after reaching third value)?
Thanks
// Thanks for very quick answers, I made mistake and posted only Problem Statement without Input Format: "three numbers separated by bunch of spaces and/or new lines"
So for example input should look like this:
2
1 4
// Ok thanks to you guys finally I made this:
n = []
while len(n) < 3:
s=input()
i = s.split()
[n.append(int(j)) for j in i]
print(2 * sum(n))
It's working but when I sent my results I got Runtime Error. I have no idea why:
Link: https://a2oj.com/p?ID=346
You could just use:
sys.argv
import sys
numbers = [int(x) for x in sys.argv[1:4]]
print(numbers)
print(sum(numbers))
When inputs are given line by line.
from sys import stdin
sum = 0
for num in stdin.readline(4):
sum = sum + int(num)
print(sum)
When inputs are given on CLI.
from sys import argv
sum = 0
for num in argv[1:4]:
sum = sum + int(num)
print(sum)
Use Python strip() and split() functions as per your usecases
I am not sure what you are looking for, but it seems that you are looking for is the input function, from python's builtins:
x=input()
This reads any input from the user, as a string. You have then to convert it to a number if needed.
You can read three values:
x=input("First value:")
y=input("Second value:")
z=input("Third value:")
As you have now specified more precisely the problem statement, I edit my answer:
In your case, this is not very complicated. I am not going to give you the answer straight away, as it would defeat the point, but the idea is to wrap the input inside a while loop. Something like:
numbers=[]
while (you have less than 3 numbers):
(input one line and add the numbers to your list)
(print the sum of your numbers)
That way you are waiting for as many inputs as you need until you reach 3 numbers. By the way, depending on your input, you might have to check whether you do not get more than 3 numbers.
After seeing the update from the question author and linked the online judge question description, the tweak to his code needed is below. It's worth noting that the expected output is in float and has precision set to 6 and the output is 2 * sum of all inputs, not just sum. There is no description on this in the online judge question and you've to understand from the input vs output.
n = []
while len(n) < 3:
s = input()
i = s.split()
n.extend(float(j) for j in i)
print(format(2 * sum(n), '.6f'))
Screenshot below
But the first version of this answer is still valid to the first version of this question. Keeping them if anyone else is looking for the following scenarios.
To separate inputs by enter aka New lines:
numbers_List = []
for i in range(3):
number = int(input())
numbers_List.append(number)
print("Sum of all numbers: ", sum(numbers_List))
Screenshot:
To separate inputs by space aka Bunch of spaces:
Use map before taking input. I'd suggest using input as well instead of sys.stdin.read() to get input from users, separated by space, and ended by pressing Enter key.
Very easy implementation below for any number of inputs and to add using sum function on a list:
numbers = list(map(int, input("Numbers: ").split()))
print("Sum of all numbers: ", sum(numbers))
The screenshot below and link to the program is here
Read Python's Built-in Functions documentation to know more about all the functions I used above.

Coin tossing simulation unexpected probabilities

This is a script I wrote to simulate a coin toss game that ends in a given fixed sequence of outcomes (tosses are either ones or zeroes). This fixed sequence characterizes the game. For example, coin_series('01') simulates a series of tosses that culminate in a 0 followed by a 1; valid outcomes are x01 where x is a string of zeroes and ones not containing the pattern 01 anywhere.
The script gives the number of throws required to terminate two games, 01 and 11, and these should have the same result since the coin is not a biased one (equal chance of outcome zero or outcome one on a toss).
Yet this is not the case, with my output being 6 and 4 respectively, of which only the first is correct. So I must have a bug in the script.
My questions are: how can I make the script a little more concise, as I hope this will help find the bug; and second, is there a bug that is apparent to all but me?
import numpy as np
class coin_series(object):
def __init__(self,win_state): #win_state is a string of ones and zeroes
self.win_state=win_state
self.d=self.draw()
self.series=[self.d.next() for i in range(len(self.win_state))]
self.n=len(self.win_state)
while not self.check():
self.play()
def draw(self):
while True:
t=np.random.rand()
if t>=0.5:
yield 1
else:
yield 0
def check(self):
return(self.win_state==''.join(map(str,self.series)))
def play(self):
self.series=self.series[1:]+[self.d.next()]
self.n+=1
if __name__=='__main__':
print np.mean([coin_series('11').n for i in range(100000)])
print np.mean([coin_series('01').n for i in range(100000)])
This is no bug, your code works just fine!
As you toss the coins, if you are aiming for a 0 then a 1 and you make the 0 but the 1 ends up being another 0, then you are still already halfway there, you are just hoping for a 1 again.
On the other hand, if you are aiming for a 1 and then a 1 and make the 1, then if you don't make the second 1, you are now on a 0 and back to waiting for a first 1.
So to reword that a different way, in the first case, if you fail, you only get reset halfway, but in the second case, if you fail then you are back to the start again - thus increasing the average number of throws to get them.
Take a look at this redit post for another explanation.
No bug. You would need to be generating separate pairs of flips for those values to be equal. If you generate a continuous sequence of flips and look at overlapping pairs, 11 takes longer to come up on average than 01.

Python guessing game hints and points systems [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm writing my first python game and trying to incorporate two extra elements but I'm unsure how to write it.
1: The idea is that the game will generate a random three digit number with the inbuilt random module (ie. 123) and the user will have 23 tries to guess the correct numbers. It will initiate by asking the user to input three digits between 0-9. I want to create a hint system so that the user knows if they are on the right track. See the example in the link below (I can't embed images apparently).
Click to see example Input/Output for hints
A "W" indicates that all of the characters in the guess are wrong.
One or more "X"s indicates that they have a correct character, but in an incorrect position
One or more "R"s indicates they have a correct character in the right position
To get this kind of hint will I need to create 3 separate numbers and combine them together to form the target number or will I still be able to do it with the following code:
target = random.randint(111, 999)
I've started writing a function that takes in the variables guess (this is what the user has entered) and target (the generated number):
def get_hint(guess, target):
This is as far as I have gotten with it. Laughable, I know. I literally have no idea if it even possible to create this hint system.
2: I would also like it to have a points system where the points start at 10000 (if the user guesses correctly first try) and decreases by 10% each incorrect guess (second guess = 9000, third guess = 8100, etc.) to two decimal places. I have it incrementing a count for the amount of guesses the user has tried so when they guess the correct number the following happens:
if guess == target:
print("Congratulations!")
print("{} was the correct answer!".format(target))
print("You guessed the correct answer in {} tries and scored {} points.".format(tries, points))
First the point system is fairly trivial: just have a score varible and modify it at each round score=score*0.9 and round it to 2 decimals when printing with "{:.2f}".format(score)
Regarding the hint system :
Having a list of three numbers will be far easier to deal with so I'll assume target and guess have one of the following format "123" or [1,2,3] (as strings can be indexed as lists)
The tricky part is doing the right comparisons because you have take care of what digit have already been matched against the target in order to give only "r" in the example case of guess=113 and target=333. Here is a function that does the job:
def hint(guess,target):
if guess == target:
print("win")
else:
#we store a list to keep track of the numbers
#already matched so we don't count them twice as x and r
r=[0]*len(target)
#first we check if there's a direct match
for i,n in enumerate(guess):
if guess[i] == target[i]:
r[i]=1
#we make new lists without the digits that matched
stripped_guess=[n for i,n in enumerate(guess) if r[i] == 0]
stripped_target=[n for i,n in enumerate(target) if r[i] == 0]
#we will now try to count the amount of x
x=0
for n in set(stripped_guess):
#we count how many time that given digit appears
# in the two lists, the smallest is our x amount
x+=min(stripped_guess.count(n),stripped_target.count(n))
if sum(r) == 0 and x == 0:
print("w")
else:
print("r"*sum(r)+"x"*x)
Some tests:
>>> hint(guess="404",target="404")
win
>>> hint("135","331")
rx
>>>hint("11123","12133")
rrrx
If you have a three-digit number in variable num, you can peel away the digits:
In [1]: num = 347
In [2]: num % 10
Out[2]: 7
In [3]: (num % 100) // 10
Out[3]: 4
In [4]: (num % 1000) // 100
Out[4]: 3
Then you can compare digits and place your Xs and Rs.

I have to write a program that calculates and displays the total score using a for loop?

I'm quite new to the for loops in Python. So, I want to write a program that asks the user to enter to enter 20 different scores and then I want the program to calculate the total and display it on the screen. How could I use a for loop to do this?
edit: I can ask the user to for the different numbers but I don't know how to then add them.
Without giving you the full code here is the pseudocode for what your code should look like
x = ask user for input
loop up till x //Or you could hard code 20 instead of x
add user input to a list
end
total = sum values in list
print total
Here are all the things you need to implement the logic
User input/output:
http://anh.cs.luc.edu/python/hands-on/3.1/handsonHtml/io.html
Loops:
https://wiki.python.org/moin/ForLoop
Summing a list:
https://docs.python.org/2/library/functions.html
Try something like this:
total = 0; # create the variable
for i in range(1,20): # iterate over values 1 to 20 as a list
total += int(input('Please enter number {0}: '.format(i)));
print("Sum of the numbers is '{0}'".format(total))
I'd suggest you go through the tutorials on the python site:
Python 3 is here https://docs.python.org/3/tutorial/index.html
Python 2 is here https://docs.python.org/2/tutorial/index.html
I could go into a lot of detail here and explain everything, however I'd only be duplicating the resources already available. Written far better than I could write them. It would be far more beneficial for you (and anyone else reading this who has a similar issue) to go through these tutorials and get familiar with the python documentation. These will give you a good foundation in the basics, and show you what the language is capable of.
Input
To read a value from the commandline you can use the input function, e.g. valueString = input("prompt text"). Notice the value stored is of type string, which is effectively an array of ASCI/Unicode characters.
So in order to perform math on the input, you first need to convert it to its numerical value - number = int(valueString) does this. So you can now add numbers together.
Adding numbers
Say you had two numbers, num1 and num2, you can just use the addition operator. For example num3 = num1 + num2. Now suppose you have a for loop and want to add a new number each time the loop executes, you can use the total += newNum operator.
total = 0
for _ in range(1,20):
num = input('> ')
total += int(num)
print(total)
I hope this helps.

Categories