I'm not sure what seems to be the problem with my code, I need some help. When I try running my program, it says invalid syntax next to my first if, I thought I may be an indentation error but nothing is working.
Here is my code:
import random
def montyHall():
car = random.randint(1,3)
guess1 = random.randint(1,3)
for i in range(1,3):
if ((not(i == car) and not(i == guess1)):
return i
newGuess = not(i) and not(guess1)
if (newGuess == car):
stay = True
elif (guess1 == car):
switch = False
return strategyOne
NUM_OF_TRIALS = 1000
stay = 0
switch = 0
for i in range(NUM_OF_TRIALS):
if(montyHall()):
stay += 1
else:
switch += 1
print("Staying wins", stay/NUM_OF_TRIALS, "% of the time")
print("Switching wins", switch/NUM_OF_TRIALS, "% of the time")
To many brackets and you do not need brackets in python.
Try changing:
if ((not(i == car) and not(i == guess1)):
to
if i != car and i != guess1:
Related
I am making a very creative tetris clone for a project with a friend and we have custom sprites for every shape (including the rotations) and we made a wall of else if statements for the rotations. It's supposed to work like this: It calls a random shape out of list of the main 7 shapes and every time the user presses "a" it changes the left facing gif of that shape using the giant el if wall. However, we ran unto an error where instead of executing the elif statements, it just skips to the last line and changes to the J shape no matter what shape was called in the random statement. Any help would be awesome, thank you! (We are still learning btw) also the rotate function is also supposed to happen when the user presses the "d" key but its supposed to change to the other direction.
import turtle as trtl
import random as rand
wn = trtl.Screen()
#configurations
tetris = trtl.Turtle()
drawer = trtl.Turtle()
background = trtl.Turtle()
starty = int(-400)
square = ("sqaure_block.gif")
s_block_normal = ("S_block_norm.gif")
s_block_standing = ("S_block_right.gif")
invert_s_block_normal = ("Z_block_norm.gif")
invert_s_block_standing = ("Z_block_right.gif")
l_block_normal = ("L_block_norm.gif")
l_block_180 = ("L_block_180.gif")
l_block_right = ("L_block_right.gif")
l_block_left = ("L_block_left.gif")
line_normal = ("line_block_norm.gif")
line_standing = ("line_block_standing.gif")
t_block_normal = ("T_block_norm.gif")
t_block_180 = ("T_block_180.gif")
t_block_right = ("T_BLOCK_RIGHT.gif")
t_block_left = ("T_block_left.gif")
j_block_normal = ("J_block_norm.gif")
j_block_180 = ("J_block_180.gif")
j_block_right = ("J_block_right.gif")
j_block_left = ("J_block_left.gif")
wn.addshape (square)
wn.addshape(s_block_normal)
wn.addshape(s_block_standing)
wn.addshape(invert_s_block_normal)
wn.addshape(invert_s_block_standing)
wn.addshape(l_block_normal)
wn.addshape(l_block_180)
wn.addshape(l_block_right)
wn.addshape(l_block_left)
wn.addshape(line_normal)
wn.addshape(line_standing)
wn.addshape(t_block_normal)
wn.addshape(t_block_180)
wn.addshape(t_block_right)
wn.addshape(t_block_left)
wn.addshape(j_block_normal)
wn.addshape(j_block_180)
wn.addshape(j_block_right)
wn.addshape(j_block_left)
Tshape = [square, s_block_normal, invert_s_block_normal, l_block_normal, line_normal, t_block_normal, j_block_normal]
squarecor = [-50, -25, -100, -50]
wn.bgcolor("lightblue")
background.speed("fastest")
background.hideturtle()
background.pu()
background.goto(-400,-200)
background.fillcolor("blue")
background.pencolor("blue")
background.begin_fill()
background.pd()
background.goto(400,-200)
background.goto(400,-350)
background.goto(-400,-350)
background.goto(-400,-200)
background.end_fill()
#sprite direction change
def sprite_right():
global tetris
tetris.hideturtle()
if (tetris.shape(s_block_normal)):
tetris.shape(s_block_standing)
elif (tetris.shape(invert_s_block_normal)):
tetris.shape(invert_s_block_standing)
elif (tetris.shape(line_normal)):
tetris.shape(line_standing)
elif (tetris.shape(l_block_normal)):
tetris.shape(l_block_right)
elif (tetris.shape(t_block_normal)):
tetris.shape(t_block_right)
elif (tetris.shape(j_block_normal)):
tetris.shape(j_block_right)
elif (tetris.shape(l_block_right)):
tetris.shape(l_block_180)
elif (tetris.shape(t_block_right)):
tetris.shape(t_block_180)
elif (tetris.shape(j_block_right)):
tetris.shape(j_block_180)
elif (tetris.shape(s_block_standing)):
tetris.shape(s_block_normal)
elif (tetris.shape(invert_s_block_standing)):
tetris.shape(invert_s_block_normal)
elif (tetris.shape(line_standing)):
tetris.shape(line_normal)
elif (tetris.shape(l_block_180)):
tetris.shape(l_block_left)
elif (tetris.shape(t_block_180)):
tetris.shape(t_block_left)
elif (tetris.shape(j_block_180)):
tetris.shape(j_block_left)
elif (tetris.shape(l_block_left)):
tetris.shape(l_block_normal)
elif (tetris.shape(t_block_left)):
tetris.shape(t_block_normal)
elif (tetris.shape(j_block_left)):
tetris.shape(j_block_normal)
tetris.showturtle()
def sprite_left():
tetris.hideturtle()
if (tetris.shape(s_block_normal)):
tetris.shape(s_block_standing)
elif (tetris.shape(invert_s_block_normal)):
tetris.shape(invert_s_block_standing)
elif (tetris.shape(line_normal)):
tetris.shape(line_standing)
elif (tetris.shape(l_block_normal)):
tetris.shape(l_block_left)
elif (tetris.shape(t_block_normal)):
tetris.shape(t_block_left)
elif (tetris.shape(j_block_normal)):
tetris.shape(j_block_left)
elif (tetris.shape(l_block_left)):
tetris.shape(l_block_180)
elif (tetris.shape(t_block_left)):
tetris.shape(t_block_180)
elif (tetris.shape(j_block_left)):
tetris.shape(j_block_180)
elif (tetris.shape(s_block_standing)):
tetris.shape(s_block_normal)
elif (tetris.shape(invert_s_block_standing)):
tetris.shape(invert_s_block_normal)
elif (tetris.shape(line_standing)):
tetris.shape(line_normal)
elif (tetris.shape(l_block_180)):
tetris.shape(l_block_right)
elif (tetris.shape(t_block_180)):
tetris.shape(t_block_right)
elif (tetris.shape(j_block_180)):
tetris.shape(j_block_right)
elif (tetris.shape(l_block_right)):
tetris.shape(l_block_normal)
elif (tetris.shape(t_block_right)):
tetris.shape(t_block_normal)
elif (tetris.shape(j_block_right)):
tetris.shape(j_block_normal)
tetris.showturtle()
'''
def (fast_down):
global tetris
tetris.setheading(270)
tetris.forward(10)
'''
#turn right
def turn_right():
tetris.speed("fastest")
tetris.setheading(0)
tetris.speed(1)
tetris.forward(10)
tetris.speed("fastest")
tetris.setheading(270)
#turn left
def turn_left():
tetris.speed("fastest")
tetris.setheading(180)
tetris.speed(1)
tetris.forward(10)
tetris.speed("fastest")
tetris.setheading(270)
#down
#tetris container/backround
drawer.pensize(5)
drawer.speed("fastest")
drawer.penup()
drawer.goto(150, 200)
drawer.pendown()
drawer.setheading(270)
drawer.forward(400)
drawer.setheading(180)
drawer.forward(300)
drawer.setheading(90)
drawer.forward(400)
drawer.hideturtle()
#game WIP!!!!!!!!!!
y = 0
space = int(1)
tracer = True
def spawn_T():
new_T=rand.choice(Tshape)
tetris.shape(t_block_180)
tetris.pu()
tetris.goto(0, 200)
tetris.setheading(270)
tetris.forward(10)
'''
if ((abs(space - starty)) < 200):
tetris.forward(2)
else:
'''
tetris.stamp()
'''
space = space =+ 1
'''
tetris.hideturtle()
tetris.goto(0,200)
tetris.showturtle()
if (y == 0):
spawn_T()
#changeing the directions of the sprites
#events
wn.onkeypress(turn_right, "Right")
wn.onkeypress(turn_left, "Left")
wn.onkeypress(sprite_right, "a")
wn.onkeypress(sprite_left, "d")
'''
wn.onkeypress(fast_down, "s")
'''
wn.listen()
wn.mainloop()
Here is the google drive file https://drive.google.com/drive/folders/1Q_zXEqm4aFHQ4RV-ZvEXCK2Wi7SHMxrW?usp=share_link
I think the indentation is wrong here. Maybe try putting the last else-statement one tab further?
Please use elif instead of the else: if formulation to get away from the bewildering indentation - here's how it should look:
def sprite_right():
global tetris
tetris.hideturtle()
if (tetris.shape(s_block_normal)):
tetris.shape(s_block_standing)
elif (tetris.shape(invert_s_block_normal)):
tetris.shape(invert_s_block_standing)
elif (tetris.shape(line_normal)):
tetris.shape(line_standing)
elif (tetris.shape(l_block_normal)):
tetris.shape(l_block_right)
elif (tetris.shape(t_block_normal)):
tetris.shape(t_block_right)
elif (tetris.shape(j_block_normal)):
tetris.shape(j_block_right)
elif (tetris.shape(l_block_right)):
tetris.shape(l_block_180)
elif (tetris.shape(t_block_right)):
tetris.shape(t_block_180)
elif (tetris.shape(j_block_right)):
tetris.shape(j_block_180)
elif (tetris.shape(s_block_standing)):
tetris.shape(s_block_normal)
elif (tetris.shape(invert_s_block_standing)):
tetris.shape(invert_s_block_normal)
elif (tetris.shape(line_standing)):
tetris.shape(line_normal)
elif (tetris.shape(l_block_180)):
tetris.shape(l_block_left)
elif (tetris.shape(t_block_180)):
tetris.shape(t_block_left)
elif (tetris.shape(j_block_180)):
tetris.shape(j_block_left)
elif (tetris.shape(l_block_left)):
tetris.shape(l_block_normal)
elif (tetris.shape(t_block_left)):
tetris.shape(t_block_normal)
elif (tetris.shape(j_block_left)):
tetris.shape(j_block_normal)
tetris.showturtle()
def sprite_left():
tetris.hideturtle()
if (tetris.shape(s_block_normal)):
tetris.shape(s_block_standing)
elif (tetris.shape(invert_s_block_normal)):
tetris.shape(invert_s_block_standing)
elif (tetris.shape(line_normal)):
tetris.shape(line_standing)
elif (tetris.shape(l_block_normal)):
tetris.shape(l_block_left)
elif (tetris.shape(t_block_normal)):
tetris.shape(t_block_left)
elif (tetris.shape(j_block_normal)):
tetris.shape(j_block_left)
elif (tetris.shape(l_block_left)):
tetris.shape(l_block_180)
elif (tetris.shape(t_block_left)):
tetris.shape(t_block_180)
elif (tetris.shape(j_block_left)):
tetris.shape(j_block_180)
elif (tetris.shape(s_block_standing)):
tetris.shape(s_block_normal)
elif (tetris.shape(invert_s_block_standing)):
tetris.shape(invert_s_block_normal)
elif (tetris.shape(line_standing)):
tetris.shape(line_normal)
elif (tetris.shape(l_block_180)):
tetris.shape(l_block_right)
elif (tetris.shape(t_block_180)):
tetris.shape(t_block_right)
elif (tetris.shape(j_block_180)):
tetris.shape(j_block_right)
elif (tetris.shape(l_block_right)):
tetris.shape(l_block_normal)
elif (tetris.shape(t_block_right)):
tetris.shape(t_block_normal)
elif (tetris.shape(j_block_right)):
tetris.shape(j_block_normal)
tetris.showturtle()
That said, because this is all the code you've provided, it's not possible to run it and examine why it's not working. Can you please provide an example of an implementation of these functions?
According to the documentation, shape() returns the current shape with no parameters, and sets it with one parameter. Therefore in:
if tetris.shape(s_block_normal):
shape(name) returns None, which is always False. So, if you change to:
if tetris.shape() == s_block_normal:
It should function as required.
Also, you can get rid of the if ladder completely by, for instance, something like:
next_left_shape = {s_block_normal: s_block_standing,
invert_s_block_normal: invert_s_block_standing,
... }
tetris.shape(next_left_shape[tetris.shape()])
When I run clear() as below it does not print the 'else' statement. It only works for the 'if' part. When I run it one indent outside, it clears without doing the print for both if and else. Please guide on where I should place it.
import random
from art import logo,vs
from game_data import data
from replit import clear
def game_question():
return random.choice(data)
def format_data(account):
account_name = account["name"]
account_description = account["description"]
account_country = account["country"]
return f"{account_name}, {account_description}, {account_country}"
def count(num_a, num_b):
if num_a > num_b:
return "a"
else:
return "b"
win = 0
play_on = False
while not play_on:
print (logo)
account_a = game_question()
account_b = game_question()
if account_a == account_b:
account_b = game_question()
num_a = account_a["follower_count"]
num_b = account_b["follower_count"]
print(f"Account A : {format_data(account_a)}")
print (vs)
print(f"Compare to Account B: {format_data(account_b)}")
ans = input("Which account has more followers? A or B: ").lower()
if ans == count(num_a,num_b):
win += 1
print ("A win")
else:
print (f"Wrong. You lose. Win = {win}")
play_on = True
clear()
The clear() function is not indented properly in else:. Try this for the if else statement
if ans == count(num_a,num_b):
win += 1
print ("A win")
else:
print (f"Wrong. You lose. Win = {win}")
play_on = True
clear()
A friend of mine told me that she needs help with some homework, I owe her a favor so I said fine, why not. she needed help with a program that checks a sequence, if the sequence is made of the same 2 chars one after the other it will print "yes" (for example "ABABABAB" or "3$3$3$3:)
The program works fine with even length strings (for example "abab") but not with odd length one ("ububu")
I made the code messy and "bad" in purpose, computers is her worst subject so I don't want it to look obvious that someone else wrote the code
the code -
def main():
StringInput = input('your string here - ')
GoodOrBad = True
L1 = StringInput[0]
L2 = StringInput[1]
i = 0
while i <= len(StringInput):
if i % 2 == 0:
if StringInput[i] == L1:
i = i + 1
else:
GoodOrBad = False
break
if i % 2 != 0:
if StringInput[i] == L2:
i = i + 1
else:
GoodOrBad = False
break
if GoodOrBad == True:
print("yes")
elif GoodOrBad != True:
print("no")
main()
I hope someone will spot the problem, thanks you if you read everything :)
How about (assuming s is your string):
len(set(s[::2]))==1 & len(set(s[1::2]))==1
It checks that there is 1 char in the even locations, and 1 char in the odd locations.
a) Showing your friend bad and messy code makes her hardly a better programmer. I suggest that you explain to her in a way that she can improve her programming skills.
b) If you check for the character at the even position and find that it is good, you increment i. After that, you check if i is odd (which it is, since you found a valid character at the even position), you check if the character is valid. Instead of checking for odd position, an else should do the trick.
You can do this using two methods->
O(n)-
def main():
StringInput = input('your string here - ')
GoodOrBad = True
L1 = StringInput[0]
L2 = StringInput[1]
i = 2
while i < len(StringInput):
l=StringInput[i]
if(l==StringInput[i-2]):
GoodOrBad=True
else:
GoodOrBad=False
i+=1
if GoodOrBad == True:
print("yes")
elif GoodOrBad == False:
print("no")
main()
Another method->
O(1)-
def main():
StringInput = input('your string here - ')
GoodOrBad = True
L1 = set(StringInput[0::2])
L2 = set(StringInput[1::2])
if len(L1)==len(L2):
print("yes")
else:
print("no")
main()
There is a lot in this that I would change, but I am just showing the minimal changes to get it to work. There are 2 issues.
You have an off by one error in the code:
i = 0
while i <= len(StringInput):
# in the loop you index into StringInput
StringInput[i]
Say you have 5 characters in StringInput. Because your while loop is going from i = 0 to i < = len(StringInput), it is going to go through the values [0, 1, 2, 3, 4, 5]. That last index is a problem since it is off the end off StringInput.
It will throw a 'string index out of range' exception.
You need to use:
while i < len(StringInput)
You also need to change the second if to an elif (actually it could just be an else, but...) so you do not try to test both in the same pass of the loop. If you go into the second if after the last char has been tested in the first if it will go out of range again.
elif i % 2 != 0:
So the corrected code would be:
def main():
StringInput = input('your string here - ')
GoodOrBad = True
L1 = StringInput[0]
L2 = StringInput[1]
i = 0
while i < len(StringInput):
if i % 2 == 0:
if StringInput[i] == L1:
i = i + 1
else:
GoodOrBad = False
break
elif i % 2 != 0:
if StringInput[i] == L2:
i = i + 1
else:
GoodOrBad = False
break
if GoodOrBad == True:
print("yes")
elif GoodOrBad != True:
print("no")
main()
def main():
StringInput = input('your string here - ')
MaxLength = len(StringInput) // 2 + (len(StringInput) % 2 > 0)
start = StringInput[:2]
chained = start * MaxLength
GoodOrBad = chained[:len(StringInput)] == StringInput
if GoodOrBad == True:
print("yes")
elif GoodOrBad != True:
print("no")
I believe this does what you want. You can make it messier if this isn't bad enough.
Ok I have a feeling that this is a simple simple issue but I have been staring at this code for about 10 hours now.
The issue I am having is in mastermind is that once I get it to recognize that I have the correct colors in the right spot I can get it to display the right spots with X and the wrong spots with O. I need to be able to convert that so instead of X and O I need it to tell the user that he/she has 2 blacks and one white
For example: The secret code is RGYB The user enters RGOY so then Python relays "You have 2 blacks(The R and G spots) and one 1 White (The Y because it's the right color just in the wrong index) As of right now I got it to display X for the right color in the right spot and anything else it is an O
I will post what I have been working with now but today I am at my wit's end
https://pastebin.com/HKK0T7bQ
if correctColor != "XXXX":
for i in range(4):
if guess[i] == tempCode[i]:
correctColor += "X"
if guess[i] != tempCode[i] in tempCode:
correctColor += "O"
print (correctColor + "\n")
if correctColor == "XXXX":
if attempts == 1:
print ("You think you are sweet because you got it right on the first try? Play me again!")
else:
print ("Well done... You needed " + str(attempts) + " attempts to guess.")
game = False
A few comments
X and O
you use X and 0 to denote the success, it will be easier and faster to use a list or tuple or booleans for this, that way you can use sum() to count how many colors and locations were correct. Then whether you represent that with X and O or red and white pins is a matter for later
compartmentalization
Your game logic (guess input, input validation, do you want to continue, etc) is mixed with the comparison logic, so it would be best to separate the different functions of your program into different methods.
This is an fineexample to introduce object oriented programming, but is so simple it doesn't need OO, but it can help. What you need is a method which takes a series of colours and compares it to another series of colours
Standard library
Python has a very extended standard library, so a lot of stuff you want to do probably already exists
Correct colours
to count the number of letters which occur in 2 strings, you can use collections.Counter
guess = "RGOY "
solution = "RGYB"
a = collections.Counter(guess)
b = collections.Counter(solution)
a & b
Counter({'G': 1, 'R': 1, 'Y': 1})
correct_colours = sum((a & b).values())
3
So the user guessed 3 colours correctly
Correct locations
can be solved with an easy list comprehension
[g == s for g, s in zip(guess, solution)]
[True, True, False, False]
sum(g == s for g, s in zip(guess, solution))
2
so the used put 2 colours on the correct location
This is a MasterMind I made in Python. Hope you like it and it helped you! :)
import random
import time
from tkinter import *
def select_level():
global level
level = level_selector.get()
root.destroy()
root = Tk()
level_selector = Scale(root, from_=1, to=3, tickinterval=1)
level_selector.set(0)
level_selector.pack()
Button(root, text="Select a difficulty level", command=select_level).pack()
mainloop()
cpc_1_digit = 0
cpc_2_digit = 0
cpc_3_digit = 0
cpc_4_digit = 0
p_1_digit = 0
p_2_digit = 0
p_3_digit = 0
p_4_digit = 0
correct_correct = 0
correct_wrong = 0
chances = 0
if level == 1:
chances = 15
elif level == 2:
chances = 10
else:
chances = 7
cpc_1_digit = random.randint(0, 9)
while cpc_2_digit == cpc_1_digit or cpc_2_digit == cpc_3_digit or cpc_2_digit ==
cpc_4_digit:
cpc_2_digit = random.randint(0, 9)
while cpc_3_digit == cpc_1_digit or cpc_3_digit == cpc_2_digit or cpc_3_digit ==
cpc_4_digit:
cpc_3_digit = random.randint(0, 9)
while cpc_4_digit == cpc_1_digit or cpc_4_digit == cpc_2_digit or cpc_4_digit ==
cpc_3_digit:
cpc_4_digit = random.randint(0, 9)
while chances > 0:
correct_correct = 0
correct_wrong = 0
answer = input("Enter a four-digit number with different digits (e.g 1476): ")
p_1_digit = int(answer[0])
p_2_digit = int(answer[1])
p_3_digit = int(answer[2])
p_4_digit = int(answer[3])
if p_1_digit == cpc_1_digit:
correct_correct = int(correct_correct) + 1
elif p_1_digit == cpc_2_digit or p_1_digit == cpc_3_digit or p_1_digit ==
cpc_4_digit:
correct_wrong = int(correct_wrong) + 1
else:
pass
if p_2_digit == cpc_2_digit:
correct_correct = correct_correct + 1
elif p_2_digit == cpc_1_digit or p_2_digit == cpc_3_digit or p_2_digit ==
cpc_4_digit:
correct_wrong = int(correct_wrong) + 1
else:
pass
if p_3_digit == cpc_3_digit:
correct_correct = int(correct_correct) + 1
elif p_3_digit == cpc_1_digit or p_3_digit == cpc_2_digit or p_3_digit ==
cpc_4_digit:
correct_wrong = int(correct_wrong) + 1
else:
pass
if p_4_digit == cpc_4_digit:
correct_correct = int(correct_correct) + 1
elif p_4_digit == cpc_1_digit or p_4_digit == cpc_3_digit or p_4_digit ==
cpc_2_digit:
correct_wrong = int(correct_wrong) + 1
else:
pass
print("")
if int(correct_correct) == 4:
print("Congratsulations! You found the computer's number!")
break
elif int(correct_wrong) > 0 or int(correct_correct) >= 1 and int(correct_correct)
< 4:
print("You got " + str(correct_correct) + " correct digit(s) in the correct
place, and " + str(correct_wrong) + " correct digit(s) but in wrong place.")
elif int(correct_correct) == 0 and int(correct_wrong) == 0:
print("You didn't guess any number, try again!")
else:
raise Exception("CheckError: line 69, something went wrong with the
comparings.")
exit()
print("")
chances = chances - 1
if chances == 0:
print("You lost... The secret number was " + str(cpc_1_digit) + str(cpc_2_digit)
+ str(cpc_3_digit) + str(cpc_4_digit) + ". Try again by rerunning the program.")
time.sleep(4)
I've been trying out to solve the monty hall problem in Python in order to advance in coding, which is why I tried to randomize everything. The thing is: I've been running into some trouble. As most of you probably know the monty problem is supposed to show that changing the door has a higher winrate (66%) than staying on the chosen door (33%). For some odd reason though my simulation shows a 33% winrate for both cases and I am not really sure why.
Here's the code:
from random import *
def doorPriceRandomizer():
door1 = randint(0,2) #If a door is defined 0, it has a price in it
door2 = randint(0,2) #If a door is defined either 1 or 2, it has a goat in it.
door3 = randint(0,2)
while door2 == door1:
door2 = randint(0,2)
while door3 == door2 or door3 == door1:
door3 = randint(0,2)
return door1,door2,door3 #This random placement generator seems to be working fine.
while True:
loopStart = 0
amountWin = 0
amountLose = 0
try:
loopEnd = int(input("How often would you like to run this simulation: "))
if loopEnd < 0:
raise ValueError
doorChangeUser = int(input("[0] = Do not change door; [1] = Change door: "))
if doorChangeUser not in range(0,2):
raise ValueError
except ValueError:
print("Invalid input. Try again.\n")
else:
while loopStart != loopEnd:
gameDoors = doorPriceRandomizer()
inputUser = randint(0,2)
if doorChangeUser == 0:
if gameDoors[inputUser] == 0:
amountWin += 1
loopStart += 1
else:
amountLose += 1
loopStart += 1
elif doorChangeUser == 1:
ChangeRandom = 0
while gameDoors[ChangeRandom] == gameDoors[inputUser]:
ChangeRandom = randint(0,2)
if gameDoors[ChangeRandom] == 0:
amountWin += 1
loopStart += 1
else:
amountLose += 1
loopStart += 1
print("Win amount: ",amountWin,"\tLose amount: ",amountLose)
What am I doing wrong? I really appreciate all help! Thanks in advance!
ChangeRandom = 0
while gameDoors[ChangeRandom] == gameDoors[inputUser]:
ChangeRandom = randint(0,2)
This doesn't do what you think it does. Instead of checking if the ChangeRandom door is the same as the inputUser door, this checks if the ChangeRandom door and the inputUser door have the same value -- that is to say they're either both winners or both losers.
That said, that's not even what you want to do. What you want to do is to find a door that's not the user's input that IS a loser door, then switch to the OTHER one that isn't the user's input. This could be implemented with minimal change to your code as:
other_wrong_door = next(c for c, v in enumerate(gameDoors) if v != 0 and c != inputUser)
new_door = next(c for c, _ in enumerate(gameDoors) if c != inputUser and c != other_wrong_door)
But honestly this merits a re-examining of your code's structure. Give me a few minutes to work something up, and I'll edit this answer to give you an idea of how I'd implement this.
import random
DOORS = [1, 0, 0]
def runonce(switch=False):
user_choice = random.choice(DOORS)
if user_choice == 1:
# immediate winner
if switch:
# if you won before and switch doors, you must lose now
return False
else:
new_doors = [0, 0] # remove the user-selected winner
new_doors = [0] # remove another loser
return bool(random.choice(new_doors))
# of course, this is always `0`, but
# sometimes it helps to show it. In production you
# wouldn't bother writing the extra lines and just return False
else:
if switch:
new_doors = [1, 0] # remove the user-selected loser
new_doors = [1] # remove another loser
return bool(random.choice(new_doors))
# as above: this is always True, but....
else:
return False # if you lost before and don't switch, well, you lost.
num_trials = int(input("How many trials?"))
no_switch_raw = [run_once(switch=False) for _ in range(num_trials)]
switch_raw = [run_once(switch=True) for _ in range(num_trials)]
no_switch_wins = sum(1 for r in no_switch_raw if r)
switch_wins = sum(1 for r in switch_raw if r)
no_switch_prob = no_switch_wins / num_trials * 100.0
switch_prob = switch_wins / num_trials * 100.0
print( " WINS LOSSES %\n"
f"SWITCH: {switch_wins:>4} {num_trials-switch_wins:>6} {switch_prob:.02f}\n"
f"NOSWITCH:{no_switch_wins:>4} {num_trials-no_switch_wins:>6} {no_switch_prob:.02f}")
You have gotten the mechanics of the problem wrong so you are getting the wrong result. I have rewritten the choice mechanics, but I am leaving the user input stuff to you so that you can continue to learn python. This is one of many ways to solve the problem, but hopefully it demonstrates some things to you.
def get_choices():
valid_choices = [0, 1, 2] # these are the values for a valid sample
shuffle(valid_choices) # now randomly shuffle that list
return valid_choices # return the shuffled list
def get_door(user_choice):
return user_choice.index(0)
def monty_sim(n, kind):
"""
:param n: number of runs in this simulation
:param kind: whether to change the door or not, 0 - don't change, 1 = change door
:return: (win_rate, 1 - win_rate)
"""
wins = 0
for i in range(0, n):
game_doors = get_choices()
user_choice = get_door(get_choices()) # use the same method and find user door choice
# so there are two branches.
# In both, a door with a goat (game_door = 1) is chosen, which reduce the result to
# a choice between two doors, rather than 3.
if kind == 0:
if user_choice == game_doors.index(0):
wins += 1
elif kind == 1:
# so now, the user chooses to change the door
if user_choice != game_doors.index(0):
wins += 1
# Because the original choice wasn't the right one, then the new
# must be correct because the host already chose the other wrong one.
win_rate = (wins / n) * 100
return win_rate, 100 - win_rate
if __name__ == '__main__':
n = 1000
kind = 1
wins, loses = monty_sim(n, kind)
print(f'In a simulation of {n} experiments, of type {kind} user won {wins:02f} of the time, lost {loses:02f} of the time')