Keeping a running total of score in python 3 - python

I am writing a program that rolls two dice; and then according to what is rolled, points are assigned; and a running total is kept. So far, I have this; but I keep running into an error of "int is not callable". Can someone please help?
import random
def dice():
a = 1
b = 6
return random.randint(a,b)
rollOne = int(dice())
rollTwo = int(dice())
def greeting():
option = input('Enter Y if you would like to roll the dice: ')
if option == 'Y':
print('You have rolled a' , rollOne, 'and a' , rollTwo)
points = []
if rollOne() == rollTwo():
points.append(10)
print('You have a total of %d points' % (sum(points)))
if rollOne == 6 or rollTwo ==6:
points.append(4)
print('You have a total of %d points' % (sum(points)))
if (rollOne + rollTwo) == 7:
points.append(2)
print('You have a total of %d points' % (sum(points)))
dice()
greeting()

The result from dice() is an integer which you have named rollOne and rollTwo.
They cannot be "called" like you have tried to do rollOne().
In order to solve the error, remove the brackets from the line (which you have done in your other if statements)
if rollOne() == rollTwo():
becomes
if rollOne == rollTwo:

Problem is in this ,
if rollOne() == rollTwo():
rollone and rolltwo are return values not functions

Related

Blackjack str iteration error

I am converting an array into a string to print, but the compiler still says not iterable.
Traceback (most recent call last):
File "python", line 157, in <module>
File "python", line 56, in total
TypeError: 'int' object is not iterable
The function total() is located on line 56, if you think it is the problem, but if you run the script, you should find that the function works properly every other instance.
import random
import time
def makeDeck():
cards = []
num = 1
for card in range(52):
cards.append(num)
num += 1
if num == 13:
num = 1
return cards
#def shuffle(cards):
#for card in cards:
#num = random.randint(0,51)
#cards.insert(0, cards[num])
#return cards
def shuffle(deck):
for card in deck:
hold = deck.pop(0)
deck.insert(random.randint(1,51),hold)
return deck
def cardToString(hand):
cardString = []
for card in hand:
if card == 1:
cardString.append('Ace')
elif card == 11:
cardString.append('Jack')
elif card == 12:
cardString.append('Queen')
elif card == 13:
cardString.append('King')
else:
cardString.append(str(card))
for card in cardString:
return card
def deal(user,deck):
hand = []
for x in range(2):
hand.append(deck.pop(0))
return hand
def deal1(user,deck):
hand = []
for card in deck:
hand.append(deck.pop(0))
return hand
def total(hand):
score = 0
for card in hand:
if(card>10):
score += 10
elif(card != 1):
score += card
else:
if(score>=11):
score+=1
else:
score+=11
return score
#def playGame():
#to do
name1 = input('Player 1, please enter your name:\n')
p2q = input('Will there be two plaers? (y/n)')
if(p2q == 'y' or p2q == 'Y' ):
p2yn = 1
name2 = input('Player 2, please enter your name:\n')
elif(p2q == 'n' or p2q == 'N'):
p2yn = 0
deck = makeDeck()
shuffle(deck)
p1hand = deal(name1,deck)
if(p2yn == 1):
p2hand = deal(name2,deck)
else:
print(end = ' ')
hs=0
print(str(name1)+', your hand is:', end = ' ' )
cardToString(p1hand)
print(str(p1hand[0])+',',p1hand[1], end = ' ')
print('and your total is', total(p1hand))
time.sleep(2)
tot1 = total(p1hand)
while(tot1 < 21):
p1cvar = input('Would you like another card? (y/n)\n')
if(p1cvar =='n' or p1cvar == 'N'):
break
else:
p1hand.append(deck.pop(0))
newCard = str(p1hand[-1])
cardToString(newCard)
print('You got a', newCard)
time.sleep(1)
print('Your total is now', total(p1hand))
time.sleep(1)
if(total(p1hand) <= 21):
hs = total(p1hand)
else:
print('You went over 21!')
p1hand=0
time.sleep(1)
break
if(p1hand != 0):
print('The high score is', total(p1hand), 'held by', str(name1)+'.')
time.sleep(1)
shuffle(deck)
if(p2yn == 1):
print(str(name2)+', your hand is:', end = ' ' )
cardToString(p2hand)
print(str(p2hand[0])+',',p2hand[1], end = ' ')
print('and your total is', total(p2hand))
time.sleep(2)
tot1 = total(p2hand)
while(tot1 < 21):
p2cvar = input('Would you like another card? (y/n)\n')
if(p2cvar =='n' or p2cvar == 'N'):
break
else:
p2hand.append(deck.pop(0))
newCard = str(p2hand[-1])
cardToString(newCard)
print('You got a', newCard)
time.sleep(1)
print('Your total is now', total(p2hand))
time.sleep(1)
if(total(p2hand)>21):
print('You went over 21!')
p2hand=0
time.sleep(1)
break
if(p2hand != 0 and total(p2hand)>hs):
print('The high score is', total(p2hand), 'held by', str(name2)+'.')
hs = total(p2hand)
time.sleep(1)
dealerHand = deal('Dealer',deck)
print("The dealer's hand is:", end = ' ' )
cardToString(dealerHand)
print(str(dealerHand[0])+',',dealerHand[1], end = ' ')
print('and their total is', total(dealerHand))
time.sleep(2)
totD = total(dealerHand)
while(totD < 21):
tdh = total(dealerHand)
if(tdh<hs and tdh<22):
dealerHand.append(deck.pop(0))
newCard = str(dealerHand[-1])
cardToString(newCard)
print('Dealer got a', newCard)
time.sleep(.5)
print("Dealer's total is now", total(dealerHand))
time.sleep(1)
if(total(dealerHand) <= 21 and total(dealerHand)>hs):
hs = total(dealerHand)
else:
print('Dealer went over 21!')
dealerHand=0
else:
break
if(dealerHand != 0):
print('The high score is', total(dealerHand), 'held by', str("Dealer")+'.')
while(total(p1hand)>21 or total(dealerHand)>21):
if(total(dealerHand)>21):
print('Dealer has been eliminated from play!')
elif(total(p1hand)>21):
print(name1,'has been eliminated from play!')
About 11 lines up from the bottom of your code block, you are setting the dealers hand to 0:
....
else:
print('Dealer went over 21!')
dealerHand=0
This is concerning since their hand should be a list. Thus when you try to iterate over it to count the total, you get that an int isn't iteratable.
Should probably be something like
dealerHand = []
Also, a few lines after that, you are asking if dealerHand!=0, when I think you mean total(dealerHand)
You should also be careful with your other assignments that change a variable from a list to an int such as
#Around line 111
print('You went over 21!')
p1hand=0
time.sleep(1)
break
.....
#Around line 140
print('You went over 21!')
p2hand=0
time.sleep(1)
break
Because Python is not strongly type, changing the type of a given variable name can lead to a lot of these kinds of problems
#Stephen gave you the direct answer. I suggest using pylint3 (or some other linter) on your code. It would have told you the problem
R:170, 6: Redefinition of dealerHand type from list to int
(redefined-variable-type)
This will help you in the future.

Python Credit Card Validation

I'm a beginner Python learner and I'm currently working on Luhn Algorithm to check credit card validation. I wrote most of the code, but I'm stuck with 2 errors I get 1st one is num is referenced before assignment. 2nd one I'm getting is object of type '_io.TextIOWrapper' has no len(). Further help/ guidance will be greatly appreciated.
These are the steps for Luhn Algorithm (Mod10 Check)
Double every second digit from right to left. If this “doubling” results in a two-digit number, add the two-digit
number to get a single digit.
Now add all single digit numbers from step 1.
Add all digits in the odd places from right to left in the credit card number.
Sum the results from steps 2 & 3.
If the result from step 4 is divisible by 10, the card number is valid; otherwise, it is invalid.
Here's what my output is supposed to be
Card Number Valid / Invalid
--------------------------------------
3710293 Invalid
5190990281925290 Invalid
3716820019271998 Valid
37168200192719989 Invalid
8102966371298364 Invalid
6823119834248189 Valid
And here is the code.
def checkSecondDigits(num):
length = len(num)
sum = 0
for i in range(length-2,-1,-2):
number = eval(num[i])
number = number * 2
if number > 9:
strNumber = str(number)
number = eval(strNumber[0]) + eval(strNumber[1])
sum += number
return sum
def odd_digits(num):
length = len(num)
sumOdd = 0
for i in range(length-1,-1,-2):
num += eval(num[i])
return sumOdd
def c_length(num):
length = len(num)
if num >= 13 and num <= 16:
if num [0] == "4" or num [0] == "5" or num [0] == "6" or (num [0] == "3" and num [1] == "7"):
return True
else:
return False
def main():
filename = input("What is the name of your input file? ")
infile= open(filename,"r")
cc = (infile.readline().strip())
print(format("Card Number", "20s"), ("Valid / Invalid"))
print("------------------------------------")
while cc!= "EXIT":
even = checkSecondDigits(num)
odd = odd_digits(num)
c_len = c_length(num)
tot = even + odd
if c_len == True and tot % 10 == 0:
print(format(cc, "20s"), format("Valid", "20s"))
else:
print(format(cc, "20s"), format("Invalid", "20s"))
num = (infile.readline().strip())
main()
You just forgot to initialize num
def main():
filename = input("What is the name of your input file? ")
infile= open(filename,"r")
# initialize num here
num = cc = (infile.readline().strip())
print(format("Card Number", "20s"), ("Valid / Invalid"))
print("------------------------------------")
while cc!= "EXIT":
even = checkSecondDigits(num)
odd = odd_digits(num)
c_len = c_length(num)
tot = even + odd
if c_len == True and tot % 10 == 0:
print(format(cc, "20s"), format("Valid", "20s"))
else:
print(format(cc, "20s"), format("Invalid", "20s"))
num = cc = (infile.readline().strip())
First, maybe you should remove the extra characters:
def format_card(card_num):
"""
Formats card numbers to remove any spaces, unnecessary characters, etc
Input: Card number, integer or string
Output: Correctly formatted card number, string
"""
import re
card_num = str(card_num)
# Regex to remove any nondigit characters
return re.sub(r"\D", "", card_num)
After check if credit card is valid using the Luhn algorithm:
def validate_card(formated_card_num):
"""
Input: Card number, integer or string
Output: Valid?, boolean
"""
double = 0
total = 0
digits = str(card_num)
for i in range(len(digits) - 1, -1, -1):
for c in str((double + 1) * int(digits[i])):
total += int(c)
double = (double + 1) % 2
return (total % 10) == 0
This is a very simpler version of code it is based on lunh's algorithm
def validator(n):
validatelist=[]
for i in n:
validatelist.append(int(i))
for i in range(0,len(n),2):
validatelist[i] = validatelist[i]*2
if validatelist[i] >= 10:
validatelist[i] = validatelist[i]//10 + validatelist[i]%10
if sum(validatelist)%10 == 0:
print('This a valid credit card')
else:
print('This is not valid credit card')
def cardnumber():
result=''
while True:
try:
result = input('Please enter the 16 digit credit card number : ')
if not (len(result) == 16) or not type(int(result) == int) :
raise Exception
except Exception:
print('That is not a proper credit card number. \nMake sure you are entering digits not characters and all the 16 digits.')
continue
else:
break
return result
def goagain():
return input('Do you want to check again? (Yes/No) : ').lower()[0] == 'y'
def main():
while True:
result = cardnumber()
validator(result)
if not goagain():
break
if __name__ == '__main__':
main()
Old thread but the answer concerns me... and the real issue wasn't identified.
Actually, the error is that you have used the identifier (num) for the parameter when defining checkSecondDigits as the identifier/name of the argument when calling the function in the mainline. The function should be called in main() by
even = checkSecondDigits(cc) so the value in cc (which is the argument) is passed into num (as the parameter) for use within the function.
The same rookie error is made with odd_digits and cc_length.
This question (and the initially suggested answer) demonstrates a fundamental mis-understanding of passing arguments to parameters...
The suggested 'declaring' of num just hides this error/misunderstanding and also obfuscates the local and global scopes of num (which should only be local) and cc (which is global) so whilst the suggestion works in this case, it works for the wrong reason and is poor style and bad programming.
Further,
num should not appear anywhere in main() as it should be local to (only appear inside of) the functions called...
The last line in this code should be the same as the first, but the last line incorrectly assigns the data to num instead of cc
cc = (infile.readline().strip())
print(format("Card Number", "20s"), ("Valid / Invalid"))
print("------------------------------------")
while cc!= "EXIT":
even = checkSecondDigits(num)
odd = odd_digits(num)
c_len = c_length(num)
tot = even + odd
if c_len == True and tot % 10 == 0:
print(format(cc, "20s"), format("Valid", "20s"))
else:
print(format(cc, "20s"), format("Invalid", "20s"))
num = (infile.readline().strip())
you can use my code for card validation it is 100% dynamic because of the card structure is stored in CSV file, so it is easy to update here is the code on GitHub profile, python file link, code explanation file link and CSV for datafile link
python code:
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 10 20:55:30 2019
#author: Preyash2047#gmail.com
"""
import csv
import numpy as np
#csv file imported and storf in reader
reader = csv.DictReader(open("card_data.csv"))
#input card number
card_number = input("Enter the card No: ")
#global variable declaration
min_digits=0
max_digits=0
card_number_list = list(card_number)
card_number_list_reverse=card_number_list[::-1]
card_number_length=len(card_number_list)
first_digit = int(card_number_list[0])
#global variable for final output
card_provider_list_number = 0
result_found = False
card_number_digits = 0
mit_name=""
#list
start=[]
end=[]
name=[]
c_d=[]
number_length=[]
min_max_digits_list=[]
#append the list from csv
for raw in reader:
start.append(raw['start'])
end.append(raw['end'])
name.append(raw['name'])
c_d.append(raw['c_d'])
number_length.append(raw['number_length'])
#initialize the value of min_digits & max_digits
def min_max_digits():
global min_digits
global max_digits
for i in range(len(start)):
available_length=number_length[i].split(',')
for j in range(len(available_length)):
min_max_digits_list.append(available_length[j])
min_max_digits_array = np.array(min_max_digits_list)
np.unique(min_max_digits_array)
min_digits=int(min(min_max_digits_array))
max_digits=int(max(min_max_digits_array))
#list to int
def list_to_int(noofdigits):
str1 = ""
return int(str1.join(noofdigits))
#card validation
def iin_identifier():
first_six_digit = list_to_int(card_number_list[0:6])
for i in range(len(start)):
if(first_six_digit >= int(start[i]) and first_six_digit <= int(end[i])):
available_length=number_length[i].split(',')
for j in range(len(available_length)):
if(card_number_length == int(available_length[j])):
global card_provider_list_number
card_provider_list_number = i
global card_number_digits
card_number_digits = available_length[j]
global result_found
result_found = True
#Major Industry Identifier (MII) identification
def mit_identifier():
global first_digit
global mit_name
switcher = {
1: "Airlines",
2: "Airlines",
3: "Travel and Entertainment",
4: "Banking and Financial Services",
5: "Banking and Financial Services",
6: "Merchandising and Banking",
7: "Petroleum",
8: "Health care, Telecommunications",
9: "National Assignment"
}
mit_name=switcher.get(first_digit, "MIT Identifier Not Found")
#Luhn Algorithm or modulo-10 Algorithm
def luhn_algorithm():
for i in range(card_number_length):
if(i%2!=0 and i!=0):
card_number_list_reverse[i]=int(card_number_list_reverse[i])*2
#print(str(i)+" "+ str(card_number_list_reverse[i]))
if(len(str(card_number_list_reverse[i]))==2):
even_number_2=list(str(card_number_list_reverse[i]))
card_number_list_reverse[i] = int(even_number_2[0])+int(even_number_2[1])
#print("\tsubsum "+str(i)+" "+str(card_number_list_reverse[i]))
else:
card_number_list_reverse[i]=int(card_number_list_reverse[i])
division_int = int(sum(card_number_list_reverse)/10)
division_float=sum(card_number_list_reverse)/10
if(division_int-division_float==0):
return True
#initial level number length validation
def card_number_validation():
min_max_digits()
if(card_number_length>= min_digits and card_number_length <= max_digits and first_digit != 0):
iin_identifier()
mit_identifier()
if(result_found and luhn_algorithm()):
print("\nEntered Details are Correct\n")
print("\nHere are the some details we know about you card")
print("\nNo: "+card_number)
print("\nIssuing Network: "+name[card_provider_list_number])
print("\nType: "+c_d[card_provider_list_number]+" Card")
print("\nCategory of the entity which issued the Card: "+mit_name)
else:
print("\nCard Number is Invalid\nPlease renter the number!\n")
else:
print("\nCard Number is Invalid\n")
#method called to run program
card_number_validation()
n = input("Enter 16-digit Credit Card Number:")
lst = []
for i in range(16):
lst.append(n[i])
# print(lst)
# list1 = n.split()
# print(list1)
def validate_credit_card():
global lst
if len(lst) == 16:
for i in range(0, len(lst)):
lst[i] = int(lst[i])
# print(lst)
last = lst[15]
first = lst[:15]
# print(first)
# print(last)
first = first[::-1]
# print(first)
for i in range(len(first)):
if i % 2 == 0:
first[i] = first[i] * 2
if first[i] > 9:
first[i] -= 9
sum_all = sum(first)
# print(first)
# print(sum_all)
t1 = sum_all % 10
t2 = t1 + last
if t2 % 10 is 0:
print("Valid Credit Card")
else:
print("Invalid Credit Card!")
else:
print("Credit Card number limit Exceeded!!!!")
exit()
if __name__ == "__main__":
validate_credit_card()

Issue with Python Slot Machine

import random
balance = 50
def generator():
slot = 0
count = 0
gen = random.random()
while count < 3:
count = count + 1
if gen <= 0.01:
slot = 'Cherry'
elif gen <= 0.06:
slot = 'Diamond'
elif gen <= 0.16:
slot = 'Heart'
elif gen <= 0.36:
slot = 'Spade'
elif gen <= 0.66:
slot = 'Club'
elif gen <= 1:
slot = 'Monkey'
else:
break
return slot
def win(generator):
if generator() == 'Monkey' and generator() == 'Monkey' and generator() == 'Monkey':
balance = balance + 2122
print "Welcome to the International Slot Machine"
print ""
print "Balance: $",balance
print ''
spinyn = (raw_input("Would you like to spin? $5 per spin. Enter y or n:\n"))
while True:
if spinyn == "y":
break
elif spinyn == "n":
print "Final Balance: $",balance
print "Thank you for using the International Slot Machine"
raise SystemExit
else:
spinyn = raw_input('\033[31mPlease enter only y or n.\033[0m\n')
spin = (raw_input("Press enter to spin for $5:\n"))
while True:
if spin == '':
balance = balance - 5
if balance <= 0:
print ""
print "Final Balance: $",balance
print "You have run out of money, the game has now ended."
raise SystemExit
print ""
print "\033[34mResult:\033[0m"
print "\033[34m-------\033[0m"
print generator()
print generator()
print generator()
print ""
print "New balance:$",balance
print ""
spinagain = (raw_input("Would you like to spin again? Press enter to spin again, type anything to exit.\n"))
while True:
if spinagain == "":
break
else:
print "Final Balance: $",balance
print "Thank you for using the International Slot Machine"
raise SystemExit
else:
spin = (raw_input("Please press enter to spin.\n"))
I'm trying to make a very basic slot machine.
My question is: How do I make the generator function repeat 3 times and return 3 outputs, and then how do I make it recognise certain combinations?
Is this possible at all, keeping with my current format?
Also, how could I incorporate arrays into my code?
Thanks
Make the generator return a list or tuple of three values after generating three values, also it would be easier to use random.choice() rather than random.random() . random.choice() randomly selects a element for a list of values/iterable with equal probability for all elements. Example -
def generator():
ret = []
for _ in range(3):
ret.append(random.choice(['Cherry','Diamond','Heart','Spade','Club','Monkey']))
return tuple(ret)
If you want to have different probabilities for different elements, you can keep the current method, just loop over that three times and append to ret like done above and return ret from it.
Then in your win function, keep a dictionary such that the key is the tuple of combination and the value is the amount the user wins, then you can simply use .get() with a default value of 0 , to get how much the user won. Do not pass in generator as an argument. Example -
def win():
roll = generator()
d = {('Monkey','Monkey','Monkey'):21222,...}
return d.get(roll,0)
Then in your main loop, call this win() function to roll and see how much the user won.
Use the range function to choose 3 times and store it in a list.
import random
choices_list=[]
for ctr in range(3):
gen = random.choice(['Cherry', 'Diamond', 'Heart',
'Spade', 'Club', 'Monkey'])
choices_list.append(gen)
print choices_list

Python number increment

I am experimenting with python, and I've made this little math game. Though I am having some issue with a scoring system. Each time the player gets an answer correct, I want the score to increment by 1. I have tried, however I haven't got it to increase each time the player gets something right.
Heres the code
import operator
import random
operations = {
"addition": ("+", operator.add),
"substraction": ("-", operator.sub),
"multiplication": ("*", operator.mul),
"division": ("/", operator.floordiv),
}
def ask_operation(difficulty, maxtries=3):
maxvalue = 5 * difficulty
x = random.randint(1, maxvalue)
y = random.randint(1, maxvalue)
op_name, (op_symbol, op_fun) = random.choice(list(operations.items()))
result = op_fun(x, y)
score = 0
print("Difficulty level %d" % difficulty)
print("Now lets do a %s calculation and see how clever you are." % op_name)
print("So what is %d %s %d?" % (x, op_symbol, y))
for ntry in range(1, 1+maxtries):
answer = int(input(">"))
if answer == result:
print("Correct!")
score += 1
print score
return True
elif ntry == maxtries:
print("That's %s incorrect answers. The end." % maxtries)
else:
print("That's not right. Try again.")
return False
def play(difficulty):
while ask_operation(difficulty):
difficulty += 1
print("Difficulty level achieved: %d" % difficulty)
play(1)
The score is reset to 0 every time in ask_operation. You should initialize it in play instead.
By the way, //Increment score// is not valid Python. You can set comments in Python like this, even in Stack Overflow.
score += 1 # Increment score

Is this a good or bad 'simulation' for Monty Hall? How come? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
Through trying to explain the Monty Hall problem to a friend during class yesterday, we ended up coding it in Python to prove that if you always swap, you will win 2/3 times. We came up with this:
import random as r
#iterations = int(raw_input("How many iterations? >> "))
iterations = 100000
doors = ["goat", "goat", "car"]
wins = 0.0
losses = 0.0
for i in range(iterations):
n = r.randrange(0,3)
choice = doors[n]
if n == 0:
#print "You chose door 1."
#print "Monty opens door 2. There is a goat behind this door."
#print "You swapped to door 3."
wins += 1
#print "You won a " + doors[2] + "\n"
elif n == 1:
#print "You chose door 2."
#print "Monty opens door 1. There is a goat behind this door."
#print "You swapped to door 3."
wins += 1
#print "You won a " + doors[2] + "\n"
elif n == 2:
#print "You chose door 3."
#print "Monty opens door 2. There is a goat behind this door."
#print "You swapped to door 1."
losses += 1
#print "You won a " + doors[0] + "\n"
else:
print "You screwed up"
percentage = (wins/iterations) * 100
print "Wins: " + str(wins)
print "Losses: " + str(losses)
print "You won " + str(percentage) + "% of the time"
My friend thought this was a good way of going about it (and is a good simulation for it), but I have my doubts and concerns. Is it actually random enough?
The problem I have with it is that the all choices are kind of hard coded in.
Is this a good or bad 'simulation' for the Monty Hall problem? How come?
Can you come up with a better version?
Your solution is fine, but if you want a stricter simulation of the problem as posed (and somewhat higher-quality Python;-), try:
import random
iterations = 100000
doors = ["goat"] * 2 + ["car"]
change_wins = 0
change_loses = 0
for i in xrange(iterations):
random.shuffle(doors)
# you pick door n:
n = random.randrange(3)
# monty picks door k, k!=n and doors[k]!="car"
sequence = range(3)
random.shuffle(sequence)
for k in sequence:
if k == n or doors[k] == "car":
continue
# now if you change, you lose iff doors[n]=="car"
if doors[n] == "car":
change_loses += 1
else:
change_wins += 1
print "Changing has %s wins and %s losses" % (change_wins, change_loses)
perc = (100.0 * change_wins) / (change_wins + change_loses)
print "IOW, by changing you win %.1f%% of the time" % perc
a typical output is:
Changing has 66721 wins and 33279 losses
IOW, by changing you win 66.7% of the time
You mentioned that all the choices are hardcoded in. But if you look closer, you'll notice that what you think are 'choices' are actually not choices at all. Monty's decision is without loss of generality since he always chooses the door with the goat behind it. Your swapping is always determined by what Monty chooses, and since Monty's "choice" was actually not a choice, neither is yours. Your simulation gives the correct results..
I like something like this.
#!/usr/bin/python
import random
CAR = 1
GOAT = 0
def one_trial( doors, switch=False ):
"""One trial of the Monty Hall contest."""
random.shuffle( doors )
first_choice = doors.pop( )
if switch==False:
return first_choice
elif doors.__contains__(CAR):
return CAR
else:
return GOAT
def n_trials( switch=False, n=10 ):
"""Play the game N times and return some stats."""
wins = 0
for n in xrange(n):
doors = [CAR, GOAT, GOAT]
wins += one_trial( doors, switch=switch )
print "won:", wins, "lost:", (n-wins), "avg:", (float(wins)/float(n))
if __name__=="__main__":
import sys
n_trials( switch=eval(sys.argv[1]), n=int(sys.argv[2]) )
$ ./montyhall.py True 10000
won: 6744 lost: 3255 avg: 0.674467446745
Here's my version ...
import random
wins = 0
for n in range(1000):
doors = [1, 2, 3]
carDoor = random.choice(doors)
playerDoor = random.choice(doors)
hostDoor = random.choice(list(set(doors) - set([carDoor, playerDoor])))
# To stick, just comment out the next line.
(playerDoor, ) = set(doors) - set([playerDoor, hostDoor]) # Player swaps doors.
if playerDoor == carDoor:
wins += 1
print str(round(wins / float(n) * 100, 2)) + '%'
Here is an interactive version:
from random import shuffle, choice
cars,goats,iters= 0, 0, 100
for i in range(iters):
doors = ['goat A', 'goat B', 'car']
shuffle(doors)
moderator_door = 'car'
#Turn 1:
selected_door = choice(doors)
print selected_door
doors.remove(selected_door)
print 'You have selected a door with an unknown object'
#Turn 2:
while moderator_door == 'car':
moderator_door = choice(doors)
doors.remove(moderator_door)
print 'Moderator has opened a door with ', moderator_door
#Turn 3:
decision=raw_input('Wanna change your door? [yn]')
if decision=='y':
prise = doors[0]
print 'You have a door with ', prise
elif decision=='n':
prise = selected_door
print 'You have a door with ', prise
else:
prise = 'ERROR'
iters += 1
print 'ERROR:unknown command'
if prise == 'car':
cars += 1
elif prise != 'ERROR':
goats += 1
print '==============================='
print ' RESULTS '
print '==============================='
print 'Goats:', goats
print 'Cars :', cars
My solution with list comprehension to simulate the problem
from random import randint
N = 1000
def simulate(N):
car_gate=[randint(1,3) for x in range(N)]
gate_sel=[randint(1,3) for x in range(N)]
score = sum([True if car_gate[i] == gate_sel[i] or ([posible_gate for posible_gate in [1,2,3] if posible_gate != gate_sel[i]][randint(0,1)] == car_gate[i]) else False for i in range(N)])
return 'you win %s of the time when you change your selection.' % (float(score) / float(N))
print simulate(N)
Not mine sample
# -*- coding: utf-8 -*-
#!/usr/bin/python -Ou
# Written by kocmuk.ru, 2008
import random
num = 10000 # number of games to play
win = 0 # init win count if donot change our first choice
for i in range(1, num): # play "num" games
if random.randint(1,3) == random.randint(1,3): # if win at first choice
win +=1 # increasing win count
print "I donot change first choice and win:", win, " games"
print "I change initial choice and win:", num-win, " games" # looses of "not_change_first_choice are wins if changing
I found this to be the most intuitive way of solving the problem.
import random
# game_show will return True/False if the participant wins/loses the car:
def game_show(knows_bayes):
doors = [i for i in range(3)]
# Let the car be behind this door
car = random.choice(doors)
# The participant chooses this door..
choice = random.choice(doors)
# ..so the host opens another (random) door with no car behind it
open_door = random.choice([i for i in doors if i not in [car, choice]])
# If the participant knows_bayes she will switch doors now
if knows_bayes:
choice = [i for i in doors if i not in [choice, open_door]][0]
# Did the participant win a car?
if choice == car:
return True
else:
return False
# Let us run the game_show() for two participants. One knows_bayes and the other does not.
wins = [0, 0]
runs = 100000
for x in range(0, runs):
if game_show(True):
wins[0] += 1
if game_show(False):
wins[1] += 1
print "If the participant knows_bayes she wins %d %% of the time." % (float(wins[0])/runs*100)
print "If the participant does NOT knows_bayes she wins %d %% of the time." % (float(wins[1])/runs*100)
This outputs something like
If the participant knows_bayes she wins 66 % of the time.
If the participant does NOT knows_bayes she wins 33 % of the time.
Read a chapter about the famous Monty Hall problem today. This is my solution.
import random
def one_round():
doors = [1,1,0] # 1==goat, 0=car
random.shuffle(doors) # shuffle doors
choice = random.randint(0,2)
return doors[choice]
#If a goat is chosen, it means the player loses if he/she does not change.
#This method returns if the player wins or loses if he/she changes. win = 1, lose = 0
def hall():
change_wins = 0
N = 10000
for index in range(0,N):
change_wins += one_round()
print change_wins
hall()
Updated solution
Update, this time using the enum module. Again, going for brevity while using the most expressive features of Python for the problem at hand:
from enum import auto, Enum
from random import randrange, shuffle
class Prize(Enum):
GOAT = auto()
CAR = auto()
items = [Prize.GOAT, Prize.GOAT, Prize.CAR]
num_trials = 100000
num_wins = 0
# Shuffle prizes behind doors. Player chooses a random door, and Monty chooses
# the first of the two remaining doors that is not a car. Then the player
# changes his choice to the remaining door that wasn't chosen yet.
# If it's a car, increment the win count.
for trial in range(num_trials):
shuffle(items)
player = randrange(len(items))
monty = next(i for i, p in enumerate(items) if i != player and p != Prize.CAR)
player = next(i for i in range(len(items)) if i not in (player, monty))
num_wins += items[player] is Prize.CAR
print(f'{num_wins}/{num_trials} = {num_wins / num_trials * 100:.2f}% wins')
Previous solution
Yet another "proof," this time with Python 3. Note the use of generators to select 1) which door Monty opens, and 2) which door the player switches to.
import random
items = ['goat', 'goat', 'car']
num_trials = 100000
num_wins = 0
for trial in range(num_trials):
random.shuffle(items)
player = random.randrange(3)
monty = next(i for i, v in enumerate(items) if i != player and v != 'car')
player = next(x for x in range(3) if x not in (player, monty))
if items[player] == 'car':
num_wins += 1
print('{}/{} = {}'.format(num_wins, num_trials, num_wins / num_trials))
Monty never opens the door with the car - that's the whole point of the show (he isn't your friend an has knowledge of what is behind each door)
Here is different variant I find most intuitive. Hope this helps!
import random
class MontyHall():
"""A Monty Hall game simulator."""
def __init__(self):
self.doors = ['Door #1', 'Door #2', 'Door #3']
self.prize_door = random.choice(self.doors)
self.contestant_choice = ""
self.monty_show = ""
self.contestant_switch = ""
self.contestant_final_choice = ""
self.outcome = ""
def Contestant_Chooses(self):
self.contestant_choice = random.choice(self.doors)
def Monty_Shows(self):
monty_choices = [door for door in self.doors if door not in [self.contestant_choice, self.prize_door]]
self.monty_show = random.choice(monty_choices)
def Contestant_Revises(self):
self.contestant_switch = random.choice([True, False])
if self.contestant_switch == True:
self.contestant_final_choice = [door for door in self.doors if door not in [self.contestant_choice, self.monty_show]][0]
else:
self.contestant_final_choice = self.contestant_choice
def Score(self):
if self.contestant_final_choice == self.prize_door:
self.outcome = "Win"
else:
self.outcome = "Lose"
def _ShowState(self):
print "-" * 50
print "Doors %s" % self.doors
print "Prize Door %s" % self.prize_door
print "Contestant Choice %s" % self.contestant_choice
print "Monty Show %s" % self.monty_show
print "Contestant Switch %s" % self.contestant_switch
print "Contestant Final Choice %s" % self.contestant_final_choice
print "Outcome %s" % self.outcome
print "-" * 50
Switch_Wins = 0
NoSwitch_Wins = 0
Switch_Lose = 0
NoSwitch_Lose = 0
for x in range(100000):
game = MontyHall()
game.Contestant_Chooses()
game.Monty_Shows()
game.Contestant_Revises()
game.Score()
# Tally Up the Scores
if game.contestant_switch and game.outcome == "Win": Switch_Wins = Switch_Wins + 1
if not(game.contestant_switch) and game.outcome == "Win": NoSwitch_Wins = NoSwitch_Wins + 1
if game.contestant_switch and game.outcome == "Lose": Switch_Lose = Switch_Lose + 1
if not(game.contestant_switch) and game.outcome == "Lose": NoSwitch_Lose = NoSwitch_Lose + 1
print Switch_Wins * 1.0 / (Switch_Wins + Switch_Lose)
print NoSwitch_Wins * 1.0 / (NoSwitch_Wins + NoSwitch_Lose)
The learning is still the same, that switching increases your chances of winning, 0.665025416127 vs 0.33554730611 from the above run.
Here's one I made earlier:
import random
def game():
"""
Set up three doors, one randomly with a car behind and two with
goats behind. Choose a door randomly, then the presenter takes away
one of the goats. Return the outcome based on whether you stuck with
your original choice or switched to the other remaining closed door.
"""
# Neither stick or switch has won yet, so set them both to False
stick = switch = False
# Set all of the doors to goats (zeroes)
doors = [ 0, 0, 0 ]
# Randomly change one of the goats for a car (one)
doors[random.randint(0, 2)] = 1
# Randomly choose one of the doors out of the three
choice = doors[random.randint(0, 2)]
# If our choice was a car (a one)
if choice == 1:
# Then stick wins
stick = True
else:
# Otherwise, because the presenter would take away the other
# goat, switching would always win.
switch = True
return (stick, switch)
I also had code to run the game many times, and stored this and the sample output in this repostory.
Here is my solution to the MontyHall problem implemented in python.
This solution makes use of numpy for speed, it also allows you to change the number of doors.
def montyhall(Trials:"Number of trials",Doors:"Amount of doors",P:"Output debug"):
N = Trials # the amount of trial
DoorSize = Doors+1
Answer = (nprand.randint(1,DoorSize,N))
OtherDoor = (nprand.randint(1,DoorSize,N))
UserDoorChoice = (nprand.randint(1,DoorSize,N))
# this will generate a second door that is not the user's selected door
C = np.where( (UserDoorChoice==OtherDoor)>0 )[0]
while (len(C)>0):
OtherDoor[C] = nprand.randint(1,DoorSize,len(C))
C = np.where( (UserDoorChoice==OtherDoor)>0 )[0]
# place the car as the other choice for when the user got it wrong
D = np.where( (UserDoorChoice!=Answer)>0 )[0]
OtherDoor[D] = Answer[D]
'''
IfUserStays = 0
IfUserChanges = 0
for n in range(0,N):
IfUserStays += 1 if Answer[n]==UserDoorChoice[n] else 0
IfUserChanges += 1 if Answer[n]==OtherDoor[n] else 0
'''
IfUserStays = float(len( np.where((Answer==UserDoorChoice)>0)[0] ))
IfUserChanges = float(len( np.where((Answer==OtherDoor)>0)[0] ))
if P:
print("Answer ="+str(Answer))
print("Other ="+str(OtherDoor))
print("UserDoorChoice="+str(UserDoorChoice))
print("OtherDoor ="+str(OtherDoor))
print("results")
print("UserDoorChoice="+str(UserDoorChoice==Answer)+" n="+str(IfUserStays)+" r="+str(IfUserStays/N))
print("OtherDoor ="+str(OtherDoor==Answer)+" n="+str(IfUserChanges)+" r="+str(IfUserChanges/N))
return IfUserStays/N, IfUserChanges/N
I just found that global ratio of winning is 50% and ratio of losing is 50%... It is how the proportion on winning or losing based on selected final option.
%Wins (staying): 16.692
%Wins (switching): 33.525
%Losses (staying) : 33.249
%Losses (switching) : 16.534
Here is my code, that differs from yours + with commented comments so you can run it with small iterations :
import random as r
#iterations = int(raw_input("How many iterations? >> "))
iterations = 100000
doors = ["goat", "goat", "car"]
wins_staying = 0
wins_switching = 0
losses_staying = 0
losses_switching = 0
for i in range(iterations):
# Shuffle the options
r.shuffle(doors)
# print("Doors configuration: ", doors)
# Host will always know where the car is
car_option = doors.index("car")
# print("car is in Option: ", car_option)
# We set the options for the user
available_options = [0, 1 , 2]
# The user selects an option
user_option = r.choice(available_options)
# print("User option is: ", user_option)
# We remove an option
if(user_option != car_option ) :
# In the case the door is a goat door on the user
# we just leave the car door and the user door
available_options = [user_option, car_option]
else:
# In the case the door is the car door
# we try to get one random door to keep
available_options.remove(available_options[car_option])
goat_option = r.choice(available_options)
available_options = [goat_option, car_option]
new_user_option = r.choice(available_options)
# print("User final decision is: ", new_user_option)
if new_user_option == car_option :
if(new_user_option == user_option) :
wins_staying += 1
else :
wins_switching += 1
else :
if(new_user_option == user_option) :
losses_staying += 1
else :
losses_switching += 1
print("%Wins (staying): " + str(wins_staying / iterations * 100))
print("%Wins (switching): " + str(wins_switching / iterations * 100))
print("%Losses (staying) : " + str(losses_staying / iterations * 100))
print("%Losses (switching) : " + str(losses_switching / iterations * 100))

Categories