Loop only adds the last result to a list - python-3.x

I am trying to run a small casino roulette betting outcome simulator. As a result I want to understand how big of a bank the casino should have in order not to go bankrupt in relation to the players betting size.
Please see code below:
from random import choices
bankroll = 500
bet = 50
lose = -50
population = [bet, lose]
weights = [0.4865, 0.5135]
game_count = 1
winning_game_count = []
bankrupt_game_count = []
for i in range(10000):
while bankroll != 0 and game_count < 5000:
result = int(choices(population, weights)[0])
bankroll -= result
game_count += 1
if game_count > 4999:
winning_game_count.append('won')
elif bankroll == 0:
bankrupt_game_count.append('lost')
print(winning_game_count)
print(bankrupt_game_count)
I am getting the result of the last iteration only, whereas I want to get the total sum of all games (5000 games) and the number of games where bankroll resulted in 0. I am lost.

You only get the result of the last iteration because you only run 1 iteration.
You need to reset the variables that control your loop condition between each iteration:
for i in range(10000):
bankroll=500
game_count = 1
while bankroll != 0 and game_count < 5000:

Related

List in Python have limit?

I'm writing a code to factor the number 600851475143 (my teacher must be mad at us). It runs normally up to position 10007 and even gives the primes 71 and 6857, but gives the error below the code below this message after that.
numero = 600851475143 #number
primos = [2,...,104729] # here is a list of 10000 primes that stackoverflow wouldn't let me insert
# ^ primes
ponteiro = 0 # pointer
cont = primos[0]
primos_usados = [] #used primes
while True:
print(f"{ponteiro} - {cont} {numero}\n{primos_usados}") # to see the values ​​per loop
if(numero%primos[cont] == 0):
numero = numero/primos[cont]
primos_usados.append(primos[cont])
ponteiro = 0
if(numero/primos[cont] == 1):
break
ponteiro += 1
cont = primos[ponteiro]
error:
if(numero%primos[cont] == 0):
IndexError: list index out of range
I manually tried to access the value primos[9999] but got the same error. how do I do this without having to either this error occur or I have to put 10000 numbers in a list?

How does a value from a previous level in recursion go back up?

I'm trying to make a recursive function to get minimum number of coins for change, but I think my understanding of what each layer's return value in the stack is wrong. What I want is for the coin amount to be passed back up when the recursion reaches it's base case, but looking at the debugger, the coin case decreases on the way back up.
I've already tried to look at solutions for this problem, but they all seem to use dynamic programming, and I know that it's more efficient in terms of complexity, but I want to figure out how to do the recursion before adding the dynamic programming portion
def min_coin(coin_list, value, counter = 0):
if value == 0:
return 0
else:
for coin in coin_list:
if coin <= value:
sub_result = value - coin
min_coin(coin_list, sub_result, counter)
counter +=1
return counter
#counter += 1 #should add returning out from,
#return counter
coin_list = [5, 2, 1]
value = 8
print(min_coin(coin_list,value))
I want an output of 3, but the actual output is 1 no matter the value
You need to increment the counter before calling min_coin().
def min_coin(coin_list, value, counter = 0):
if value == 0:
return counter
else:
for coin in coin_list:
if coin <= value:
sub_result = value - coin
return min_coin(coin_list, sub_result, counter+1)
You can solve your task without recursion, answer from geekforcoders
# Python 3 program to find minimum
# number of denominations
def findMin(V):
# All denominations of Indian Currency
deno = [1, 2, 5, 10, 20, 50,
100, 500, 1000]
n = len(deno)
# Initialize Result
ans = []
# Traverse through all denomination
i = n - 1
while(i >= 0):
# Find denominations
while (V >= deno[i]):
V -= deno[i]
ans.append(deno[i])
i -= 1
# Print result
for i in range(len(ans)):
print(ans[i], end = " ")
# Driver Code
if __name__ == '__main__':
n = 93
print("Following is minimal number",
"of change for", n, ": ", end = "")
findMin(n)

Count not incrementing properly in python while loop

Can anyone tell me why when I input 1, 2, 3, and 4 into this code, my output is 6, 2, 3.00? I thought that every time my while loop evaluated to true it would increment the count by one, but the output is not making sense. It's taking the total of 3 of the numbers, but only 2 for the count? I'm probably just overlooking something so an extra pair of eyes would be awesome.
def calcAverage(total, count):
average = float(total)/float(count)
return format(average, ',.2f')
def inputPositiveInteger():
str_in = input("Please enter a positive integer, anything else to quit: ")
if not str_in.isdigit():
return -1
else:
try:
pos_int = int(str_in)
return pos_int
except:
return -1
def main():
total = 0
count = 0
while inputPositiveInteger() != -1:
total += inputPositiveInteger()
count += 1
else:
if count != 0:
print(total)
print(count)
print(calcAverage(total, count))
main()
The error with your code is that on this piece of code...
while inputPositiveInteger() != -1:
total += inputPositiveInteger()
You first call inputPositiveInteger and throw out the result in your condition. You need to store the result, otherwise one input out of two is ignored and the other is added even if it is -1.
num = inputPositiveInteger()
while num != -1:
total += num
count += 1
num = inputPositiveInteger()
Improvements
Although, note that your code can be significantly improved. See the comments in the following improved version of your code.
def calcAverage(total, count):
# In Python3, / is a float division you do not need a float cast
average = total / count
return format(average, ',.2f')
def inputPositiveInteger():
str_int = input("Please enter a positive integer, anything else to quit: ")
# If str_int.isdigit() returns True you can safely assume the int cast will work
return int(str_int) if str_int.isdigit() else -1
# In Python, we usually rely on this format to run the main script
if __name__ == '__main__':
# Using the second form of iter is a neat way to loop over user inputs
nums = iter(inputPositiveInteger, -1)
sum_ = sum(nums)
print(sum_)
print(len(nums))
print(calcAverage(sum_, len(nums)))
One detail worth reading about in the above code is the second form of iter.

How can I optimize this python code for sorting large input?

I am trying to solve this problem on HackerRank which requires you to sort a list of integers and find how many times a number was moved in order to place in the correct ascending order (bribes within the context of the problem).
My code passes 8 of the 12 test cases but fails when the input is too large with a timeout error. This seems to be a common indicator on HackerRank that the code is too slow for the problem at hand. So is there a way to optimize this code so that it runs faster on larger data sets?
def minimum_bribes(queue):
"""Returns the minimum number of bribes people in a queue accepted."""
# Variable to keep track of bribes
bribes = 0
# Check if queue is too chaotic
for i in queue:
index = queue.index(i)
if i - index > 3:
return "Too chaotic"
# Use a bubble sort to find number of bribes
for i in range(len(queue) - 1):
for j in range(len(queue) - 1 - i):
if queue[j] > queue[j + 1]:
queue[j], queue[j + 1] = queue[j + 1], queue[j]
bribes += 1
return bribes
# Number of test cases
t = int(input())
results = []
for _ in range(t):
# Number of people
n = int(input())
# Final State of queue
q = list(map(int, input().rstrip().split()))
# Add bribe counts to results array
results.append(minimum_bribes(q))
# Print results
for result in results:
print(result)
I would recommend using while loop to test the condition, if there was no swap in the previous iteration, there is no need to run a new swap iteration.
def minimumBribes(queue):
for i in queue:
index = queue.index(i)
if (i - index) > 3:
print("Too chaotic")
return
n = len(queue)
swap =0
swapped = True
j =0
while swapped:
j+=1
swapped = False
for i in range(n-j):
if queue[i] > queue[i+1]:
queue[i], queue[i+1] = queue[i+1], queue[i]
swap +=1
swapped = True
print(swap)
return swap

Simulating n games of craps in python

I'm pretty new to python and I have been trying to make this simulator that creates a simulator for "games" of craps. My professor wanted it to be made in the most basic form possible which is the reason for having a function for rolling one dice then another. For some reason I can't get my simOneGame function to cooperate and I can't even get it to print a value when I assign a variable to it although it should print a 1 or 0. Here is my code:
def main():
x = eval(input("how many games will be played?: "))
y = simNGames(x)
print(y)
def simOneGame():
win = 0
lose = 0
x = rollDice()
if x == 2 or x == 3 or x == 12:
lose += 1
elif x == 7 or x == 11:
win += 1
y = rollDice()
while y != 7 or y != x :
y = rollDice()
if y == x:
win += 1
elif y == 7 :
lose += 1
if win > lose:
return(1)
else:
return(0)
def simNGames(n):
wins = 0
loses = 0
x = simOneGame()
for i in range(n):
if x > 0:
wins += 1
else:
pass
frac = wins / n
return float(frac)
def rollDice():
return rollDie() + rollDie()
def rollDie():
return randrange(1,7)
I don't get an answer unless input a number greater than 100 and it's always a 1.0
There are several issues I see with your code.
First off, your simNGames only actually simulates one game, but then it adds up that game's results n times. You need to move your x = simOneGame() line inside the loop so that it gets called repeatedly.
There's a separate issue with your simOneGame function's logic. A single craps game is either won or lost, there's no scoring. That means you don't need to be adding up win and loss values. You should change all the places where you do win += 1 to do return 1 instead, and all the places that do lose += 1 should be return 0 (this means you can get rid of the rest of the code dealing with the win and lose variables too).
You also might consider returning True and False rather than 1 and 0, but this might have been decided by your teacher, and it's more a design style point than an error.
Finally, I think the while loop in simOneGame needs an and rather than an or to make the logic work correctly.

Resources