I want to write simple martingale system to count how much money will be there in "my" account after x spins on the roulette. The program is simple and just for experiment. So far I have this but, I want to add that if that random number a is for example two times or more... the same as d I would double my bet. So if.. a = 2 and a = 5 I would bet 4 instead of two and so on 8,16,32..
from random import*
money = 100
bet = 2
d = [0, 2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35]
for i in range(100):
a = randint(1, 36)
if a in d:
money -= bet
else:
money += bet
print("Your money",money,"€")
Keep a repeat variable, and use that to see if you got a in d consecutively.
from random import randint # Bad practice to import *
money = 100
bet = 2
# Consider revising the below to sets, which are faster for membership tests
d = [0, 2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35]
repeat = False
for _ in range(100): # You never use the loop variable, so denote that by naming it _
a = randint(1, 36) # btw, you have 0 in d but your randint starts from 1...
if a in d:
money -= bet
if repeat:
bet *= 2
repeat = True
else:
money += bet
repeat = False
print("Your money",money,"€")
You didn't specify what happens to the bet value when you lose a bet. The above simply keeps raising stakes if you win a bet consecutively. The bet value will not go down when you lose.
If you want to reset the bet value, you would just store that data in a separate variable like original_bet and reset with bet = original_bet within the else clause.
Related
I have this code here and I'm looking for a way to check if min_score and max_score changes, and count how many times it changes. I can't seem to find a way to do it:
games = int(input())
score = list(input().split())
score = [int(x) for x in score]
for y in range(1, len(score) + 1):
min_score = (str(min(score[:y])) + " MIN")
max_score = (str(max(score[:y])) + " MAX")
print(min_score)
print(max_score)
This is a sample test case for reference:
9
10 5 20 20 4 5 2 25 1
First number is the size of the array, which in my code I never use because I make an array just from the string of numbers below ( in fact I don't even know why they give the size).
Basically I need to find how many times the max and min values change. I'm still a beginner in programming and I don't really know what to do..
you could just keep track of the lowest and highest number encountered and check if the current score is just below or above. A simple script could look like this:
scores = [10,5,20,20,4,5,2,25,1]
countChanges = 0
limitLow = float("inf")
limitHigh = -float("inf")
for s in scores:
if(s < limitLow):
countChanges += 1
limitLow = s
if(s > limitHigh):
countChanges += 1
limitHigh = s
print("current score: %3d limits: [%2d .. %2d] changes:%d" % (s, limitLow, limitHigh, countChanges))
spam = [10, 5, 20, 20, 4, 5, 2, 25, 1]
print(sum(n < min(spam[:idx]) for idx, n in enumerate(spam[1:], start=1)))
print(sum(n > max(spam[:idx]) for idx, n in enumerate(spam[1:], start=1)))
output
4
2
if you also want to account for initial value - add 1.
Looks like a hankerrank problem? They often give the length of the input to allow solutions without knowing about built-in methods like len().
Anyway,
You can initialise min and max to the first element of the array (if it exists, check the specification), or some suitably small and large values (again, check the possible values).
Then you can count the number of times min and max changes as you go.
Should be easy enough to adapt for the case that you just want to track any change, not min and max separately. It wasn't clear from your question.
scores = [10, 5, 20, 20, 4, 5, 2, 25, 1]
min_score = scores[0]
max_score = scores[0]
min_score_changes = 0
max_score_changes = 0
for score in scores:
if score < min_score:
min_score = score
min_score_changes += 1
if score > max_score:
max_score = score
max_score_changes += 1
I solved it like this after some thinking:
games = int(input())
score = list(input().split())
score = [int(x) for x in score]
min_score_list, max_score_list = [] , []
for y in range(1, len(score) + 1):
min_score = (min(score[:y]))
max_score = (max(score[:y]))
if min_score not in min_score_list:
min_score_list.append(min_score)
if max_score not in max_score_list:
max_score_list.append(max_score)
print((len(max_score_list) - 1), len(min_score_list) - 1)
I know it's not perfect code but at least I did myself :D
im very new to python and cant figure out a basic matching game using lottery numbers.
i have 6 numbers. the first 5 numbers are between 1-49 and the last number is 1-7.
i cant seem to loop through where after it checks it, it generates another random number.
edited:
how do i remove duplicates from range(0,4)?
import random
def lottery(ticket):
count = 0
run = True
while count < 200:
lottoNum = sorted([random.randint(1,49) for x in range(5)])
lottoNum.append(random.randint(1,7))
if lottoNum != ticket:
count += 1
print(lottoNum)
else:
run = False
print(lottoNum, count)
lottery([11, 12, 36, 39, 46, 1])
You should move the lottoNum definition inside the while loop in order to update it every loop, like this:
import random
def lottery(ticket):
count = 0
while count < 1000:
lottoNum = [random.randint(1, 49) for x in range(6)]
lottoNum[-1] = random.randint(1, 7)
if lottoNum != ticket:
count += 1
print(lottoNum)
print(lottery([11, 12, 36, 39, 46, 1]))
With this correction, you allow 1000 attempts to the lottery function to guess the correct input, stored in ticket.
Moreover, you lottery function does not have a return statement (it returns nothing), so, in Python, such a function returns a value None. This is the reason why there is no point in printing the 'result' of the function in the line print(lottery([11, 12, 36, 39, 46, 1])): this print statement will print always None because your function lottery does not returns anything.
import random
def lottery(ticket):
"""
Compare lottery ticket against lottery draws and print how many draws have taken place
to match the ticket.
"""
count = 0
run = True
while run:
lotto_num = [random.randint(1, 49) for _ in range(6)]
lotto_num[-1] = random.randint(1, 7)
if lotto_num != ticket:
print(f"No match! Your ticket {ticket}, Lottery ticket {lotto_num}")
count += 1
else:
print(f"Match! Your ticket {ticket} lottery ticket {lotto_num}")
print(f"{count} draws")
run = False
lottery([11, 12, 36, 39, 46, 1])
I am programming a lotto simulator where the code generates 6 random unique numbers out of 45 for both the winning numbers and 1000 players, both of which are stored as lists.
What I would like to do is calculate the number of winners per division.
So 1st division if all 6 winning numbers equal to the 6 numbers the player has, 2nd division if any 5 of the 6 winning numbers equal to the 5 of the 6 numbers the player has, 3rd division if any 4 of the 6 winning numbers equal to the 4 of the 6 numbers the player has, so on.
Currently my code only looks for 1st division and does not count how many times a match (if any) of 6/6 is found. This is where I get stuck how do I do this while also needing to find matches of 5/6, 4/6, 3/6.
I am using a binary search algorithm to compare the winning numbers against the numbers the player has.
winNum = [37, 10, 36, 26, 19, 43]
lotto = [[5, 19, 21, 24, 30, 38], [10, 11, 15, 24, 32, 34], ...]
# Calculates the total number of winners for each division.
def totalWinners():
target = winNum
search = binarySearch
i = 0
for i in range(len(lotto)):
found = search(target, lotto, 0, len(lotto)-1)
if found == -1:
print(lotto[i])
print("search unsuccessful...")
#Binary search algorithm.
def binarySearch (target, p, left, right):
l = left
r = right
while l <= r:
f = (l+r)//2
if target == p[f]:
return f
elif target < p[f]:
r = f - 1
else:
l = f + 1
return -1
Thank you for the help.
This seems like a better job for sets. You get easier and efficient calculation of intersections for free.
winNumSet = set(winNum)
for entry in lotto:
division = len(set(entry) & winNumSet)
That tells you what "division" that entry is in. Deal with it in whatever manner is most appropriate for your overall goal.
Obviously if you have control over how winNum and the elements of lotto are generated, it would be more efficient to start with sets in the first place.
If i've got 2 variables that contain the price needed, and the value of coins provided in cents. E.G, coins = [5, 5, 10, 20, 50, 100, 100, 200], and total = 250. I've tried a number of approaches, but I can't seem to find anything that works properly.
For example, if i've got coins = [10, 10, 20, 20, 20, 100, 100] and total = 250 it returns [10, 20, 20, 100, 100], ordering not important.
I've been trying find a solution to this for a while. Thanks for any help
For this to work, you would have to sort your coins in descending order, or use reversed(coinList) instead of coinList in the first for loop and vice versa in the second if you would like to sort them forwards:
total = 250
value = 0
coins = []
coinList = [100, 100, 20, 20, 20, 10, 10]
for coin in coinList:
if value + coin <= total:
value += coin
coins.append(coin)
else:
continue
if value >= total:
break
else:
for coin in reversed(coinList):
value += coin
coins.append(coin)
if value >= total:
break
print coins
I have a function defined below that prints each integer in the list, and it works perfectly. What I would like to do is create a second function that would call on or reutilize the int_list() function to display a sum of the list that's been generated.
I am not sure if that has been inherently performed by the code itself - I am rather new to the Python syntax.
integer_list = [5, 10, 15, 20, 25, 30, 35, 40, 45]
def int_list(self):
for n in integer_list
index = 0
index += n
print index
In your code, you're setting index=0 in every loop, so it should be initialized before the for loop:
def int_list(grades): #list is passed to the function
summ = 0
for n in grades:
summ += n
print summ
output:
int_list([5, 10, 15, 20, 25, 30, 35, 40, 45])
5
15
30
50
75
105
140
180
225
To get the sum of a list of integers you have a few choices. Obviously the easiest way is sum, but I guess you want to learn how to do it yourself. Another way is to store the sum as you add it up:
def sumlist(alist):
"""Get the sum of a list of numbers."""
total = 0 # start with zero
for val in alist: # iterate over each value in the list
# (ignore the indices – you don't need 'em)
total += val # add val to the running total
return total # when you've exhausted the list, return the grand total
A third option is reduce, which is a function that itself takes a function and applies it to the running total and each consecutive argument.
def add(x,y):
"""Return the sum of x and y. (Actually this does the same thing as int.__add__)"""
print '--> %d + %d =>' % (x,y) # Illustrate what reduce is actually doing.
return x + y
total = reduce(add, [0,2,4,6,8,10,12])
--> 0 + 2 =>
--> 2 + 4 =>
--> 6 + 6 =>
--> 12 + 8 =>
--> 20 + 10 =>
--> 30 + 12 =>
print total
42
integer_list = [5, 10, 15, 20, 25, 30, 35, 40, 45] #this is your list
x=0 #in python count start with 0
for y in integer_list: #use for loop to get count
x+=y #start to count 5 to 45
print (x) #sum of the list
print ((x)/(len(integer_list))) #average
list = [5, 10, 15, 20, 25, 30, 35, 40, 45]
#counter
count = 0
total = 0
for number in list:
count += 1
total += number
#don'n need indent
print(total)
print(count)
# average
average = total / count
print(average)
You can used reduce function from functools module
from functools import module
s=reduce(lambda x,y:x+y, integer_list)
output
225