Using Random To Assign Chance - python

Is there a way to set up an if statement like this where 1 if statement covers multiple integers?
variable = random.randrange(1,10)
if variable is between 1 - 3
then do this
if variable is between 4-5
then do this
if variable is between 6-9
then do this
or maybe something like this
a = 1,2,3,4,5,6,7,8,9,10
variable = random.randrange(1,10)
if variable == a:
then do this

What about choosing a random number for each player, then the player with the largest value gets to attack first.
Or, if this isn't turn based, then set a threshold, and if the random number is over the threshold, then the player can attack.
The threshold could also be a random number. For example:
player1.attack = randn ()
[player2 etc]
minval = randn ()
for player in players:
if player.attack > minval:
[...attack...]
The question at the bottom is easy to implement, basically exactly as you've written it:
variable = random.randrange(1,10)
if 0 <= variable < 3:
then do this
if 3 <= variable < 5:
then do this
if 5 <= variable < 9:
then do this

Related

players roll 2 dice till one reaches 100

Each player roll two dice in a row on one turn. The amount of dice obtained is
added to the player's total points. The game ends when one of the players
the first has achieved at least 100 points.
from random import randint
dicesum2 = 0
dicesum1 = 0
while (dicesum1 < 100):
dice1 = [randint(1, 6) for i in range(2)]
dicesum1 += sum(dice1)
print('player 1',dice1,'|',dicesum1)
dice2 = [randint(1, 6) for i in range(2)]
dicesum2 += sum(dice2)
print('player 2',dice2,'|',dicesum2)
i need it to end when one reaches 100. how do i check both?
if a player throws exactly one single, he loses the points obtained in the turn;
how do i check when one of the generated numbers is 1?
I need it to end when one reaches 100. how do i check both?
Learn about what the or logical operator does:
dicesum1 < 100 or dicesum2 < 100
how do i check when one of the generated numbers is 1?
Learn what the in operator does:
if 1 in dice1:
# Apply penalty.
Take a look at this and see if it helps out
from random import randint
def roll():
return [randint(1, 6) for i in range(2)]
def check_for_one(rolls):
for roll in rolls:
# this could be simplified to "if 1 in rolls", this was just my preference
if roll == 1:
return True
return False
dicesum2 = 0
dicesum1 = 0
while True:
d1 = roll()
dicesum1 += sum(d1)
if check_for_one(d1):
print(f"Player 1 rolled a 1 in batch: {d1}")
print(f"Player 1 roll: {d1} | {dicesum1}")
d2 = roll()
dicesum2 += sum(d2)
if check_for_one(d2):
print(f"Player 2 rolled a 1 in batch: {d2}")
print(f"Player 2 roll: {d2} | {dicesum2}")
if dicesum1 >= 100:
print(f"Player 1 won with: {dicesum1}")
break
elif dicesum2 >= 100:
print(f"Player 2 won with: {dicesum2}")
break
So in this example, we shove the roll out to a function and check_for_one which iterates the list you are making checking for ones and returning a boolean.
I changed the loop to while True so the loop wasn't responsible for the more complex condition which can be limiting.
For each player, it performs the roll, sums, checks and reports if a 1 is in the batch, reports the roll.
Finally it checks for the winner and breaks if one is at or over 100, reporting their win.
You can change the while condition as follow :
while (dicesum1 < 100 and dicesum2 < 100):
Alternatively, you can also use break :
...
if dicesum1 >= 100:
break
...
if dicesum2 >= 100:
break

Python- If statements with random numbers not working

I'm very new to programming and I'm trying to write a program in python 3.6 that generates a random number as an "answer" and then the computer has to guess that answer for x number of questions. To keep track of how many questions the computer guesses right, I created a variable called 'right' and if the computer's answer equals the guess, then add one to that variable. However, it does it everytime even if it's wrong. Sorry if this seems stupid, but thank you for your help
import random
def total(x, t):
for i in range(t):
cor = 0
gue = 0
n = 0
right = 0
def ans():
cor = random.randint(1,4)
print(cor, 'answer')
def guess():
gue = random.randint(1,4)
print(gue, 'guess')
while n <= x:
ans()
guess()
if cor == gue:
right += 1
n += 1
print(right, n)
I tried to slightly modify your code by moving the ans() and guess() functions outside the total(x,t) function since they seem independent from each other. Previously ans and guess were generating cor and gue randomly but not returning their values to be used in the if statement which was always using the initial values of 0. Now by saving the returned values as cor = ans() and gue = guess(), the initialised values of 0 for cor and gue are overwritten.
import random
def ans():
cor = random.randint(1,4)
print(cor, 'answer')
return cor
def guess():
gue = random.randint(1,4)
print(gue, 'guess')
return gue
def total(x, t):
for i in range(t):
cor = 0
gue = 0
n = 0
right = 0
while n <= x:
cor = ans()
gue = guess()
if cor == gue:
right += 1
n += 1
print(right, n)
print (total(2,3))
Output
1 answer
2 guess
3 answer
4 guess
1 answer
4 guess
0 3
3 answer
2 guess
1 answer
4 guess
3 answer
2 guess
0 3
2 answer
2 guess
2 answer
3 guess
3 answer
4 guess
1 3
Nesting functions like ans and guess can be useful but I'd steer clear of it while beginning programming. It makes your program harder to understand.
Here's my stab at what you are trying to do (if I've understood correctly!)
import random
# Play number_of_games_to_play of the number guessing game allowing a maximum of max_guesses per game played.
def play(number_of_games_to_play, max_guesses):
num_games = 0
guessed_right = 0
while num_games < number_of_games_to_play:
if guess_number(max_guesses):
guessed_right += 1
num_games += 1
print('\n\nI played', num_games, 'games and guessed right', guessed_right, 'times')
# Generate a random number, try and guess it up to max_guesses times. Returns whether the number was guessed correctly or not.
def guess_number(max_guesses):
answer = random.randint(1, 4)
print('\n\nPlaying guess_number. The right answer is', answer)
num_guesses = 0
while num_guesses < max_guesses:
guess = random.randint(1, 4)
print('The computer guesses', guess)
if guess == answer:
print('That is right!')
return True
else:
print('That is wrong')
num_guesses += 1
return False
play(number_of_games_to_play = 5, max_guesses = 4)
I think the you are having problems with the scope of the variables: cor and gue inside the functions are different from those outside them. Your functions are not changing the values of cor and gue, they are creating two new variables (named also cor and gue) that live only within them. For that reason, cor and gue are always 0, the condition in the if statement is always true, and you increment rigth every time.
To solve this issue, you could pass the variables as parameters to the functions.
The problem comes from variable scope. The variable core defined in method ans is different from variable core initalized in the for loop.
A better way is to do:
import random
def ans():
c = random.randint(1, 4)
return c
def guess():
g = random.randint(1, 4)
return g
def total(x, t):
for i in range(t):
n = 0
right = 0
while n <= x:
cor = ans()
gue = guess()
if (cor == gue):
right += 1
print("Answer: %6d Guess: %6d Right: %d" % (cor, gue, right))
n += 1
print(right, n)

how to output my functions numeric values as a list in python

here is my function:
def seq_sum(n):
""" input: n, generate a sequence of n random coin flips
output: return the number of heads
Hint: For simplicity, use 1,0 to represent head,tails
"""
flip = 0
heads = 0
while flip <= n:
coin = random.randint(0,2)
flip += 1
if coin == 1:
heads += 1
print(heads)
the output looks like this:
55
1
0
2
1
and so on. but what I want is the number of heads, plus a LIST of the output:
55
[1, 0, 2, 1, .....]
when I tried print(list(heads))I get the following error message:
TypeError: 'int' object is not iterable
In your function, you are merely keeping track of the total number of heads and not their history. You need to create an iterable collection to hold the interim values, such as a list or Numpy Array.
import numpy as np
def seq_sum(n):
flips = np.random.randint(low=0, high=2, size=n)
return sum(flips), flips.tolist()
# Example usage.
total_heads, flips = seq_sum(n=10)
Note that the start and end points are inclusive and exclusive, respectively, for numpy's randint function.
Hope this code will do what you want
def seq_sum(n):
flips = [random.randint(0, 1) for _ in range(n)]
return sum(flips), flips
Usage
s, l = seq_sum(10)
From the comment in your code I can tell that the function should return only the number of heads so
def seq_sum(n):
return sum(random.randint(0, 1) for _ in range(n))
import random
# edit in place
def seq_sum(n):
""" input: n, generate a sequence of n random coin flips
output: return the number of heads
Hint: For simplicity, use 1,0 to represent head,tails
"""
flip = 0
heads = 0
seq = list()
while flip <= n:
coin = random.randint(0,2)
seq.append(coin)
flip += 1
if coin == 1:
heads += 1
print(heads,seq)
#solution 2
def seq_sum(n):
flip = 0
seq = list() #create a list to store every random value
while flip < n: # if want to generate n values, the while loop only need compare 0,1,2,...n-1 times, so you need <, not <=.
coin = random.randint(0,1) # coin has only two sides
seq.append(coin)
flip += 1
return seq
# print(heads) # it is not good idea to print data in function.
random_list = seq_sum(55)
head_num = sum(random_list)
I don't know if I understood correctly, but here's my quite simple solution.
import random
def seq_sum(n):
""" input: n, generate a sequence of n random coin flips
output: return the number of heads
Hint: For simplicity, use 1,0 to represent head,tails
"""
flip = 0
heads = 0
outcomes=[]
while flip < n:
coin = random.randint(0,2)
outcomes.append(coin)
flip += 1
if coin == 1:
heads += 1
print(heads)
print(outcomes)
--------
output in console:
>>>seq_sum(3)
>>>2
>>>[1, 2, 1]
when I tried print(list(heads))I get the following error message:
TypeError: 'int' object is not iterable
Let's start with here. heads is always an integer from beginning till the end. Thus, when you put list( ) around heads, Python is complaining that you are feeding list an integer, which is not iterable.
Takeaway 1: some objects can only take certain kinds of arguments.
Second stop: I want to have a list to store the heads and tails. What should I do? One way is to create a list to store it.
my_list = [] # or list()
To add to the list, you can use append method. append method adds one element to the end of the list.
my_list.append(1)
# now my_list is [1]
my_list.append(0)
# now my_list looks like [1, 0]
Third goal: I want to randomly generate 0s and 1s to represent tails and heads. Are you really doing what you want to do? Be careful about the functions you call, especially those you are not familiar with. Read about what do the functions do.
random.randint(a, b)
Return a random integer N such that a <= N <= b. -- documentation for randint
randint(0, 2) will generate 0, 1, 2 randomly, which can represent head, tail, and... ohhh we don't have 3 things to represent.
Goal 4: Do you want to return/save the values for later use? or just print it out? Think about it and make the decision. Do you know you can turn 2 things/more at a time?
def bar():
return 1, 2
c = bar() # c is a tuple that holds two values, 0 and 1 now!
# c[0] == 1 # access the first element with index 0
# c[1] == 2
Hope with these, you can code your own answer.

Python, Asking Questions without repeats

#TODO: QUESTION 1
num = random.randint(1, 100)
print(num)
# Male or Female probabilities = 35%
if num > 0 and num <= 18:
femaleCheck(People)
printPeopleList(People)
if num > 18 and num <= 35:
maleCheck(People)
printPeopleList(People)
# Wearing a T-Shirt probabilities = 15%
if num > 35 and num <= 50:
tShirtCheck(People)
printPeopleList(People)
#Eye Color probabilities 25%
if num > 50 and num <= 63:
eyeColorBrownCheck(People)
printPeopleList(People)
if num > 63 and num <= 75:
eyeColorBlueCheck(People)
printPeopleList(People)
#Showing Teeth probabilities 25%
if num > 75 and num <= 100:
showingTeethCheck(People)
printPeopleList(People)
Here is a small portion of the code for a guess who game that I creating. As it is currently implemented it chooses a random number from a list and asks the corresponding number to carry out a function. Once question 1 is asked I would like it to ask Question 2 out of the remaining available options. Question 3 will include the remaining 2 options, and also introduce a new function to ask. I am struggling to figure out which method would be most efficient; I know that I could just indent each question following, but that would be terribly messy and hard to read. Is there some method I could use to make the following questions asked in a simplistic manner? Potentially removing that range from random integer?
If you're using 3.6 you can use random.choices with the weights keyword argument against your functions.
checkFunction = random.choices([femaleCheck, maleCheck, tShirtCheck, ...], weights=[35, 15, 25, ...])
checkFunction(People)
printPeopleList(People)
If not, check out this answer on how to implement something similar.

PYTHON parameter passing with lists

When passing a parameter into my function, it will not recognize the list and output the string.
The game is called pass the pigs, and it is required to output a state that the pig lands on.
I know in places that the code is inefficient, though this is due to the fact that I have been trying different methods that have no succeeded :(
Thanks in advance for any help!
Here is code:
norolls = int(input("Enter the number of rolls: "))
counter = 0
def roll(nothrows,counter):
rollList = []
while counter < nothrows:
rollrand = randint(0,100)
rollList.append(rollrand)
counter = (counter + 1)
return rollList
rollList = roll(norolls,counter)
rollList = list(map(int, rollList))
listlen = len(rollList)
def rollout(List, listpos, ListLen):
listpos = 0
for x in range(ListLen):
if List[listpos] == 1< 35:
print("Pink")
elif List[listpos] == 35 < 65:
print("Dot")
elif List[listpos] == 65< 85:
print("Razorback")
elif List[listpos] == 85 < 95:
print("Trotter")
elif List[listpos] == 95 < 99:
print("Snouter")
else:
List[listpos] == 99 < 100
print("Leaning Jewler")
listpos = (listpos + 1)
rollout(rollList, counter, listlen)
I'm assuming you want if List[listpos] == 1< 35 to mean List[listpos] is between 1 and 35, with 35 not being included.
The way to write that is:
if 1 <= List[listpos] < 35:
But, in your case, you don't really need a 3 level condition, since the only the first true if statement will run. So, you can just simply do:
if List[listpos] < 35:
print("Pink")
elif List[listpos] < 65:
...
and so on.
I have too low reputation to comment, but I'm going to try and clarify the code a little and give my answer.
For starters, one thing you should know is that list is a reserved name, so I don't recommend passing it as an argument to any function. You should be passing rollList to rollout(), since that is the list that you are creating. The way to pass a list as an argument is like this:
list_name = [1,2,3,4,5]
def function_name(myList=[]):
for x in myList:
print x
function_name(list_name)
Note the myList=[] in the function definition.
I would also get rid of counter and listlen as arguments, since you are setting counter to 0 at the beginning of the function, and listlen can be found with the len() function.
Secondly, for your equality statements, type them in like this:
if list_name[listpos] >= 1 and list_name[listpos] < 35
I'm sure there's a shorter way to do it, but this would help you visualize it as a range of values.
Since there are only 100 possible rolls (you do not assign an interpretation to 0) there is an alternative approach: replace the if-elif-else change with a lookup table mapping rolls to names. The code below does this. It also creates a list of rolls with a list comprehension.
from random import randint
rollmap = [None]
for sublist in (35*['Pink'], 30*['Dot'], 20*['Razorback'],
10*['Trotter'], 4*['Snouter'], 1*['Leaning Jewler']):
rollmap.extend(sublist)
n = int(input("Enter the number of rolls: "))
rolls = [randint(1, len(rollmap-1)) for i in range(n)]
for roll in rolls:
print(rollmap[roll])

Categories

Resources