Python Blackjack Game how to carry a variable in a while loop - python

I'm still deep into the making of my Blackjack game in Python, my aim is to allow the computer to 'twist' (Take another card) until the total value is greater than 15. From then onwards I want it so that as the total of the cards gets higher, the chance of the computer taking another card gets smaller just like a human (taking a risk if the number isn't TOO big).The following code occurs after the computer has been dealt two values.
if (computerCardValueTotal < 15):
print ("The computer has decided to twist")
ranCompCard3 = random.choice(availableCards)
computerCardValueTotal = ranCompCard + ranCompCard2 + ranCompCard3
if (computerCardValueTotal < 15):
print ("The computer has chosen to twist again")
My aim is to have this piece of code loop if the total value is less than 15 so that the computer twists until it is over 15. I have considered using a while loop but I'm unsure on how to carry the current total to the start of the loop so that the next card value is added to the current total. Does anyone have a solution they could help me out with?
Also, secondly, it's not the biggest of the two issues in this question, but how would you recommend doing the computer so that the chance of it twisting again is smaller as the total value of cards get bigger? For example, for if the value of the cards totals at 17, there's a 1/10 chance of the computer twisting but if the total value of the cards is 19 the chance of the computer twisting is 1/20.
All valuable help will be voted up and as always, thanks in advance! :)

You have hobbled yourself by making e.g. ranCompCard, ranCompCard2, ranCompCard3, ... when a list would make life much easier:
compCards = [ranCompCard, ranCompCard2]
while sum(compCards) < 15:
compCards.append(random.choice(availableCards))
For adjusting the probability of picking another card, you could do something like:
while True:
gap = 21 - sum(compCards)
if gap > 0 and random.random() < (1 / (40 / float(gap))):
compCards.append(random.choice(availableCards))
else:
break
Note that this is a linear relationship between gap and the probability of picking another card:
>>> for card_sum in range(15, 21):
print card_sum, 1 / (40 / float(21 - card_sum))
15 0.15
16 0.125
17 0.1
18 0.075
19 0.05
20 0.025
but you can adjust the equation as needed.
While you're editing your code, take a look at (and consider following) the official style guide; variable names should be lowercase_with_underscores.

Simply reassign the value when it changes.
while computerCardValueTotal < 15:
# other code
computerCardValueTotal = <new value>

Related

Bisect Search to choose best savings rate

Hi I would like some help with this questions set as one of the problems on the MIT OCW Computer Science and Python Course. I know people have asked similar questions and I have found useful posts such as Bisection search code doesnt work but I am still stuck!
I have struggled with this problem for many days and tried to tackle it in different ways and failed in all ways. If at all possible, could somebody just hint at where I am going wrong, rather than telling me the answer. I would like to solve this problem for myself with bit of help.
For reference, the question is part C, here: https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-0001-introduction-to-computer-science-and-programming-in-python-fall-2016/assignments/MIT6_0001F16_ps1.pdf
As I have been struggling, I have broken down this task into an overall aim and then into steps to solve the problem.
Aim: try to find the best rate of savings to achieve a down payment on a $1M house in 36 months ##Steps to solve the problem:
1) make a guess on the savings rate, which is the average of the 0 and 1000
2) calculate how that would grow over 36 months
3a) if amount reached goes over 25% of $1m within 36 months, then a lower savings rate should be the new guess
...max=guess (old guess) and min=0 and update the guess (average of high and low)
...run the calculation in step 2 with the new guess
3b) if amount does not reach 25% of $1m within 36 months, then a higher savings rate should be the new guess
...min=guess (old guess) and update the guess (average of high and low)
...run the calculation in step 2 with the new guess
3c) if amount reaches 25% of $1m within the 36th month deadline then quit and record the savings rate as the best guess.
For simplicity: assume no interest and assume wages remain same
So here's my code with the current effort at solving this. (it leads to the "guess" variable tending to 0 and then infinitely looping)
total_cost=1000000 #cost of house
portion_down_payment=0.25 #fraction of cost needed for downpayment on house
downpayment=total_cost*portion_down_payment
starting_annual_salary=float(input("Enter the starting salary: "))
low=0
high=1000
bisect_steps=0
month=1 #set as 1 because the first calculation will occur in month 1
guess=(low+high)//2
current_savings=0
def calSavings(current_savings,monthly_salary,guess,month):
while month<37:
monthly_savings=monthly_salary*(guess/1000)
current_savings+=monthly_savings
month+=1
return(current_savings)
current_savings=calSavings(current_savings,monthly_salary,guess,1)
while True:
current_savings=calSavings(current_savings,monthly_salary,guess,1)
if current_savings>downpayment and month<=35: #if amount reached goes over 25% of $1m within 36 months
#a lower savings rate should be the new guess
high=guess #max=guess (old guess) and min=0 and update the guess
bisect_steps+=1
guess=(low+high)//2
print("The guess was too high, so the new lower guess is",guess," This is bisect step",bisect_steps)
continue #send new guess up to beginning of while loop to calculate
elif current_savings<downpayment and month>=36: #if amount does not reach 25% of $1m within 36 months
low=guess
bisect_steps=+1
guess=(low+high)//2
print("The guess was too low, so the new higher guess is",guess," This is bisect step",bisect_steps)
continue #send new guess up to beginning of while loop to calculate
elif current_savings>=downpayment and month==36: #if amount reaches 25% of $1m in the 36th months then quit
# record the savings rate as the best guess
print("The best savings rate is ",guess/100,"%, the amount saved was ",current_savings," in ",month," months")
break #break out of while loop
I know other people have asked similar questions (I have looked at those answers and still not solved my problem) but more than an answer I want help on HOW to solve this problem.
Update
The reason why your loop isn't stopping is because you aren't giving it enough time. What you are forgetting is that you're dealing with the decimal type. Using the == with decimal values is always dangerous. The decimal type is accurate (by default) to 28 places, which means you're trying to find an extremely good approximation for this problem, because only when it's correct to 28 decimals will (current_savings>downpayment or current_savings<downpayment) evaluate to False invoking your exit condition.
Basically, the issue that's causing your problem is that even when you eventually get the estimate of $1,000,000.0000000001, python says this is not equal to $1,000,000.0000000000, so it keeps going until it gets the next 0, but then it just adds another zero and so on. This will continue for a very very long time and in rare cases might never stop due to the fact that not all decimal numbers can be stored as binary numbers (1,000,000 is not among those cases).
So, how do we solve this? There are two options. The easiest one is to ignore cents and just cast your comparison values to int, this will make sure that any value off by a fraction of a dollar will be accepted. The other options is to create a range of accepted answers. Say for example, I'd like to save EXACTLY $1 million in those 36 months, but that isn't likely to happen. So, instead, I'll settle for any amount in the range $1,000,000.00 - $1,000,010.00 (for example). This way, we ensure that any guess that is way too high will get rejected and only a very limited amount of guesses are accepted.
Regardless of which route you go, it is generally a good idea to put the exit condition of an infinite loop to the top, this way you guarantee that it will always be evaluated.
My suggestion would be to write a function like this and use that for your condition to exit the loop (which you would place at the top):
def are_decimals_equal(a, b):
accuracy = 0.0001
return abs(a-b) < accuracy
This will consider 0.00009 (and all decimals less than that) to be equal to 0.0000.
Original
First off, just as a note, what you're doing is not called bisection, it's called binary search.
Now to the problem, you are never altering the value of month in your main loop. This means, as soon as current_savings>downpayment evaluates to False, your program will go into an infinite loop as none of the conditions after it could evaluate to True as month>=36 will always be False.
From what I can see, the second part of your conditions in the if/elif statements is unnecessary, your calSavings will always compute 36 months worth of savings, never more, never less. Thus, if you remove that condition from your if/elif statements, your program will eventually stop and at that point it should settle on the correct answer.
Lastly, the reason why you're seeing 0 as the output is your division at the end. If you do print(typeof(guess)) you will see it is an integer, 100 is also an integer, thus this division will result in some value like 0.3123 which will get truncated to 0. Change your output to float(guess/100) and this will go away.
I hope it's okay for me to provide an answer to my own question here - though it's not a perfect answer.
The results the code produces seem plausible.
total_cost=1000000 #cost of house
portion_down_payment=0.25 #fraction of cost needed for downpayment on house
downpayment=total_cost*portion_down_payment
starting_annual_salary=float(input("Enter the starting salary: "))
monthly_salary=starting_annual_salary/12
low=0
high=1000
binary=0
month=1 #set as 1 because the first calculation will occur in month 1
guess=(low+high)//2
current_savings=0
tolerance=500
def calSavings(current_savings,monthly_salary,guess,month):
while month<37:
monthly_savings=int(monthly_salary*(guess/1000))
current_savings+=monthly_savings
month+=1
return(current_savings)
current_savings=calSavings(current_savings,monthly_salary,guess,1)
while True:
if abs(current_savings-downpayment)<=tolerance: #if the difference between the current savings and downpayment is less than $500
# record the savings rate as the best guess
print("The best savings rate is ",guess/10,"%, the amount saved was $",current_savings," in 36 months")
break #break out of while loop
elif (current_savings-downpayment)>tolerance: #if amount reached goes over 25% of $1m within 36 months
#a lower savings rate should be the new guess
high=guess #high=guess (old guess) and low=low (stays same) and update the guess
binary=binary+1
guess=(low+high)//2
print("The guess was too high, so the new lower savings rate is",guess/10,"%. This is binary-search step",binary)
current_savings=calSavings(0,monthly_salary,guess,1)
continue #send new guess up to beginning of while loop to check if conditionals
elif (downpayment-current_savings)>tolerance: #if amount does not come to within tolerance amount of 25% of $1m within 36 months
low=guess #to make the guess higher, make low=guess (old guess) and high stay the same
binary=binary+1
guess=(low+high)//2
print("guess is ",guess)
if guess>=990: #check if the savings rate guess is getting too high
print("Your wages are too low. You can't save up enough")
break #exit the while loop because conditions will never be met
print("The guess was too low, so the new higher savings rate is",guess/10,"%. This is binary-search step",binary)
current_savings=calSavings(0,monthly_salary,guess,1)
continue #send new guess up to beginning of while loop to check over the conditionals
The tolerance for an acceptable answer is within $500, but if I lower that to $50, I end up in a seemingly infinite loop again, where the guess and the low end up being the same. I am happy that I've made some apparent progress, but baffled that I can't lower the tolerance without it going haywire again.
BTW, I didn't want to seem like I ignored Nick's comments about making the variables into floats, but I explained why I worked in integers in my comment - does that seem correct?

Breaking a rod into small pieces; recursion step returns nothing useful

I have been learning python by myself and recursion is troublesome. We are given a starting piece of weight 2.0. When the piece weight is =< 0.1, we return a count of 1 piece. Otherwise, break the piece into 2, 3, or 4 pieces (quantity chosen randomly) and recur. Return the total count of pieces when all are no larger than 0.1. So far my code looks like this.
import random as rand
def breaker_function(weight_of_piece):
if weight_of_piece <= 0.1:
return 1 #returns one piece
else:
return breaker_function(weight_of_piece/rand.randint(2,4))
However, this code does not work. I ran it through the debugger, and when it reached the recursive step, the program broke it randomly (which were not less than 0.1). Since the pieces were not less than 0.1, the function stopped. I am not getting an error.
I have also tried double recursion(?) such as:
return breaker_function(breaker_function(weight_of_piece/rand.randint(2,4)))
I have also tried to store the random pieces in a list, but that just complicated things, and got a similar result.
Test case: a starting piece of size 1.0 i should get approximately 18 pieces.
Your function never returns anything but 1. You need to change the recursion step. Break into equal pieces, and then add the results of breaking each of those pieces:
else:
quant = rand.randint(2,4)
count = 0
for i in range(quant):
count += breaker_function(weight_of_piece/quant)
return count
Running this 10 times:
21
22
22
17
20
25
15
18
20
17

Why does this not seem to be random?

I was running a procedure to be like one of those games were people try to guess a number between 0 and 100 where there are 100 people guessing.I then averaged how many different guesses there are.
import random
def averager(times):
tests=[]
for i in range(times):
l=[]
for i in range(0,100):
l.append(random.randint(0,100))
tests.append(len(set(l)))
return (sum(tests))/len(tests)
print(averager(1000))
For some reason, the number of different guesses averages out to 63.6
Why is this?Is it due to a flaw in the python random library?
In a scenario where people were guessing a number between 1 and 10
The first person has a 100% chance to guess a previously unguessed number
The second person has a 90% chance to guess a previously unguessed number
The third person has a 80% chance to guess a previously unguessed number
and so on...
The average chance of guessing a new number(by my reasoning) is 55%.
But the data doesn't reflect this.
Your code is for finding the average number of unique guesses made by 100 people each guessing a number from 1 to 100.
As for why it converges to a number around 63... you should post your question to the math Stack Exchange.
If this was a completely flat distribution, you would expect the average to come out as 100, meaning everybody's guess was different. However, you know that such a scenario is much less random than a scenario where you have duplication. The fact that you get repeated numbers during a random sequence should be comforting.
All you are doing here is measuring some kind of uniqueness within very small sets: ie 1000 repeats of an experiment involving 100 random values. You might get a better appreciation of this if you use some sort of bootstrapping algorithm to sample from.
Also, if you scale up the number of repeats to millions, and perhaps measure the sample distribution (not just the mean), you'll have a little more confidence in the results you're getting.
It may be that the pseudo-random generator has a characteristic which yields approximately 60-70% non-repeated values inside a sequence the same length as the range. However, you would need to experiment with far more samples, as well as different random seeds. Otherwise your results are meaningless.
I modified your code so it would take an already generated sequence as input, rather than calculating random numbers:
def averager(seqs):
tests = []
for s in seqs:
tests.append(len(set(s)))
return float(sum(tests))/len(tests)
Then I made a function to return all possible choices for any given number of people and guess range:
def combos(n, limit):
return itertools.product(*((range(limit),) * n))
(One of the things I love about Python is that it's so easy to break apart a function into trivial pieces.)
Then I started testing with increasing numbers:
for n in range(2,100):
x = averager(combos(n, n))
print n, x, x/n
2 1.5 0.75
3 2.11111111111 0.703703703704
4 2.734375 0.68359375
5 3.3616 0.67232
6 3.99061213992 0.66510202332
7 4.62058326038 0.660083322911
8 5.25112867355 0.656391084194
This algorithm has a horrible complexity, so at this point I got a MemoryError. As you can see, the percentage of unique results keeps dropping as the number of people and guess range keeps increasing.
Repeating the test with random numbers:
def rands(repeats, n, limit):
for i in range(repeats):
yield [random.randint(0, limit) for j in range(n)]
for n in range(10, 101, 10):
x = averager(rands(10000, n, n))
print n, x, x/n
10 6.7752 0.67752
20 13.0751 0.653755
30 19.4131 0.647103333333
40 25.7309 0.6432725
50 32.0471 0.640942
60 38.3333 0.638888333333
70 44.6882 0.638402857143
80 50.948 0.63685
90 57.3525 0.63725
100 63.6322 0.636322
As you can see the results are consistent with what we saw earlier and with your own observation. I'm sure a bit of combinatorial math could explain it all.

Checking if number is within more or less range in Python

I'm new to Python as part of an exercise I'm making a simple number guessing game. I've gotten the basics covered, but I'm trying to implement a manner which tells the user if their guess is close or far from the right number. I can't guess within a range because the number to be guessed is randomly selected each time. My exercise tells me to look into abs(), but that doesn't bring me much sense. It also mentions something about within(), which also doesn't do much for me. Just need a push in the right direction if anyone can help. Thanks.
You have to come up with values that mean close or far.
It might look something like this:
diff = abs(guess - random_number)
if diff >= 50:
print("Really cold!")
elif diff >= 40:
print("Cold.")
...
elif diff >= 5:
print("Getting really hot!")
You could have a function return a number which represents how hot or cold it is (0 through 10 for example), then have a dict that looks like this:
hot_str = {
0: "You guessed it!",
1: "Extremely hot!",
10: "Frozen cold!",
}
print(hot_str[heat(diff)])
You could use operator chaining and test against both extremes of your range:
if lower <= number <= upper:
This test matches if number is in the range [lower, upper] (both ends inclusive).
If you wanted to see how close a value is to something else, you could use abs(target - guess):
distance = abs(target - guess)
if 10 <= distance <= 20:
print('You are getting closer now!')
A whole series of such tests are going to be tedious; you can print messages based on how close they are with a sequence of tests:
messages = (
(100, 'Way, way off!'),
(80, 'So cold, are you not freezing?'),
(60, 'Is there a light on the horizon?'),
(40, 'Where there is warmth, there is hope!'),
(30, 'You are getting warmer now..'),
(20, 'Is it just me, or is it getting hot in here?'),
(10, 'You are about to burn yourself!'),
(0, 'Fire, ta-cha-ta, burning desire, ta-cha-ta!')
)
distance = abs(target - guess)
if distance == 0:
print("You guessed it right!")
else:
for target, message in messages:
if distance > target:
print(message)
break
It depends on how you define close and far. For now I assume let d be parameter and if abs(guess-right_num) is less than d then it is close otherwise it is far
so the code can be:
if abs(guess-right_num) < d:
print("close")
else:
print("far")
You can't use a range to directly compare your number and the randomly generated number, but you can use a range to directly compare their differences.
abs() can be used to return the positive version of a number whether it is positive or negative.
abs(10)
10
abs(-10)
10
You can use this to ensure your random number is always positive.
You must be misreading about within(); This is either something accessible only to you and your class, or you misread what it meant, because within() is not a build-in function.
Now, on solving your problem. This takes a bit of math and logic.
You can't work within a range because the number is randomly generated. But you can always get a percentage of them and work based on that.
As an example, consider this number line, where the random number is 10 (denoted by |).
[(0)---------|---------(20)]
You will always be able to divide the number you guess by the random number and get a number that will range from (in this case) (0/10) and (10/20). In all cases, when number_guessed == number_generated, the number calculated in the division operation will be equal to 1.
I leave you to figure out the implementation of this, but the basic concept is that you can figure out how close you are to the number based on how far away you are from the number 1.
It's not perfect either, but it's an interested and clever way that might get a professor's notice, if you do it right.

Probability exercise returning different result that expected

As an exercise I'm writing a program to calculate the odds of rolling 5 die with the same number. The idea is to get the result via simulation as opposed to simple math though. My program is this:
# rollFive.py
from random import *
def main():
n = input("Please enter the number of sims to run: ")
hits = simNRolls(n)
hits = float(hits)
n = float(n)
prob = hits/n
print "The odds of rolling 5 of the same number are", prob
def simNRolls(n):
hits = 0
for i in range(n):
hits = hits + diceRoll()
return hits
def diceRoll():
firstDie = randrange(1,7,1)
for i in range(4):
nextDie = randrange(1,7,1)
if nextDie!=firstDie:
success = 0
break
else:
success = 1
return success
The problem is that running this program with a value for n of 1 000 000 gives me a probability usually between 0.0006 and 0.0008 while my math makes me believe I should be getting an answer closer to 0.0001286 (aka (1/6)^5).
Is there something wrong with my program? Or am I making some basic mistake with the math here? Or would I find my result revert closer to the right answer if I were able to run the program over larger iterations?
The probability of getting a particular number five times is (1/6)^5, but the probability of getting any five numbers the same is (1/6)^4.
There are two ways to see this.
First, the probability of getting all 1's, for example, is (1/6)^5 since there is only one way out of six to get a 1. Multiply that by five dice, and you get (1/6)^5. But, since there are six possible numbers to get the same, then there are six ways to succeed, which is 6((1/6)^5) or (1/6)^4.
Looked at another way, it doesn't matter what the first roll gives, so we exclude it. Then we have to match that number with the four remaining rolls, the probability of which is (1/6)^4.
Your math is wrong. The probability of getting five dice with the same number is 6*(1/6)^5 = 0.0007716.
Very simply, there are 6 ** 5 possible outcomes from rolling 5 dice, and only 6 of those outcomes are successful, so the answer is 6.0 / 6 ** 5
I think your expected probability is wrong, as you've stated the problem. (1/6)^5 is the probability of rolling some specific number 5 times in a row; (1/6)^4 is the probability of rolling any number 5 times in a row (because the first roll is always "successful" -- that is, the first roll will always result in some number).
>>> (1.0/6.0)**4
0.00077160493827160479
Compare to running your program with 1 million iterations:
[me#host:~] python roll5.py
Please enter the number of sims to run: 1000000
The odds of rolling 5 of the same number are 0.000755

Categories

Resources