Home > database >  How to create the opposite string in Python?
How to create the opposite string in Python?

Time:11-12

I am kinda new to Python and I am trying to run some tests with the most basic roulette strategy. So, the main idea of my strategy is this: you bet on a random color (red or black). Take red for example. If the result on the roulette wheel is also red, you change your bet to black. However, if the ball hits the opposite color, black in our example, you don't change the color, but double your bet and continue until your color appears on the roulette wheel. So I managed to create a roulette simulation, however I am a little bit struggling with the part, when my color appears on the roulette wheel and I need to change the color on the opposite one.

import random

start_money = 100
coef = 0.001
win = 0
loss = 0
money = start_money
colors = ["red", "red", "red", "red", "red", "red",
          "red", "red", "red", "red", "red", "red",
          "red", "red", "red", "red", "red", "red",
          "black", "black", "black", "black", "black", "black",
          "black", "black", "black", "black", "black", "black",
          "black", "black", "black", "black", "black", "black", "zero"]

while money > 0:
    bet = start_money * coef
    if bet > money:
        bet = money
    money -= bet
    bet_color = random.choice(["red", "black"])
    result = random.choice(colors)
    if result == bet_color:
        money  = bet * 2
        win  = 1
    else:
        loss  = 1
games = win   loss

This is how it looks now. But I don't really have any ideas on how to change color if my bet won without writing conditions for each possible result I could get.

CodePudding user response:

Define a function that returns the opposite color:

def other_color(color):
    if color == 'red':
        return 'black'
    else:
        return 'red'

Then when you want to change colors, you can use

bet_color = other_color(bet_color)

Or you could just do this as a one-liner using the conditional operator:

bet_color = 'red' if bet_color == 'black' else 'black'
  • Related