【问题标题】:How to create the opposite string in Python?如何在 Python 中创建相反的字符串?
【发布时间】:2021-11-09 22:39:47
【问题描述】:

我对 Python 有点陌生,我正在尝试使用最基本的轮盘赌策略进行一些测试。所以,我的策略的主要思想是:你赌一个随机的颜色(红色或黑色)。以红色为例。如果轮盘赌的结果也是红色,您将赌注改为黑色。但是,如果球击中相反的颜色,在我们的示例中为黑色,则您不会更改颜色,而是将赌注加倍并继续,直到您的颜色出现在轮盘上。 所以我设法创建了一个轮盘模拟,但是当我的颜色出现在轮盘上并且我需要更改对面的颜色时,我有点挣扎。

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

这就是现在的样子。但是,如果我的赌注赢了,我真的不知道如何改变颜色而不为我可能得到的每个可能的结果写条件。

【问题讨论】:

    标签: python function simulation


    【解决方案1】:

    定义一个返回相反颜色的函数:

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

    然后当你想改变颜色时,你可以使用

    bet_color = other_color(bet_color)
    

    或者您可以使用条件运算符作为单行符来执行此操作:

    bet_color = 'red' if bet_color == 'black' else 'black'
    

    【讨论】:

    • 太棒了!非常感谢!
    猜你喜欢
    • 2012-10-26
    • 1970-01-01
    • 1970-01-01
    • 2014-03-03
    • 1970-01-01
    • 2016-02-17
    • 2021-04-03
    • 2019-01-05
    • 2018-07-27
    相关资源
    最近更新 更多