Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/342.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
有人能帮我解释一下这个Python程序中的函数吗_Python_Function_Statistics_Dice - Fatal编程技术网

有人能帮我解释一下这个Python程序中的函数吗

有人能帮我解释一下这个Python程序中的函数吗,python,function,statistics,dice,Python,Function,Statistics,Dice,我试图学习如何在更复杂但不太复杂的Python程序中使用算法和统计数据。 我一直在寻找一些有趣的例子,我想尝试自己制作,我在Github上找到了这个例子。可悲的是,我无法与制作它的人建立联系,所以我希望这里的人能为我解释一些事情。 我了解这个节目的大部分内容。这几乎是一个更高级的三人掷骰子游戏,它根据对手选择的骰子,返回哪个骰子获胜的最佳和最差概率的统计数据。 让我先向您展示整个代码 from random import randint rounds = 100 dice = {

我试图学习如何在更复杂但不太复杂的Python程序中使用算法和统计数据。 我一直在寻找一些有趣的例子,我想尝试自己制作,我在Github上找到了这个例子。可悲的是,我无法与制作它的人建立联系,所以我希望这里的人能为我解释一些事情。 我了解这个节目的大部分内容。这几乎是一个更高级的三人掷骰子游戏,它根据对手选择的骰子,返回哪个骰子获胜的最佳和最差概率的统计数据。 让我先向您展示整个代码

    from random import randint

rounds = 100
dice = {
    "red": [0, 0, 4, 4, 8, 8],
    "green": [2, 2, 3, 3, 7, 7],
    "blue": [1, 1, 5, 5, 6, 6]
}


def runGame(p1, p2):
    die1 = dice[p1]
    die2 = dice[p2]

    return 1 if die1[randint(0, 5)] > die2[randint(0, 5)] else 2


def getWinner(r, b, g):
    if max(r, b, g) == r:
        return "red"
    elif max(b, g) == b:
        return "blue"
    else:
        return "green"


def getLoser(r, b, g):
    if min(r, b, g) == r:
        return "red"
    elif min(b, g) == b:
        return "blue"
    else:
        return "green"


# Simulate all possible game states with two players

# the key represents the die chosen by opponents, the value is itself a dict with win rates
# eg {"blue" : 0.45, "green" : 0.68}
results = {
    "red": {},
    "blue": {},
    "green": {}
}

print("Running %d simulations for every combination of two players..." % rounds, end="")

for opponent in results.keys():

    remaining = list(dice.keys())
    remaining.remove(opponent)

    for player in remaining:
        wins = 0

        for _ in range(rounds):
            if runGame(player, opponent) == 1:
                wins += 1

        results[opponent][player] = wins / rounds

print("completed.")

for die in dice.keys():
    rem = list(dice.keys())
    rem.remove(die)

    if results[die][rem[0]] > results[die][rem[1]]:
        print("If opponent chooses the %s dice, we should choose the %s dice, giving us %.2f%% chance of victory, "
              "as opposed to %.2f%% chance with the %s dice." % (die, rem[0], results[die][rem[0]] * 100, results[die][
            rem[1]] * 100, rem[1]))
    else:
        print("If opponent chooses the %s dice, we should choose the %s dice, giving us %.2f%% chance of victory, "
              "as opposed to %.2f%% chance with the %s dice." % (die, rem[1], results[die][rem[1]] * 100,
                                                                results[die][rem[0]] * 100, rem[0]))

# initialise a result dictionary for the three player game
results3Player = {}
for die in dice.keys():
    results3Player[die] = {
        "wins": 0,
        "losses": 0
    }

print("\nNow running %d simulations for 3 players" % rounds)

for _ in range(rounds):
    # Simulate the 3 player game
    red = dice["red"][randint(0, 5)]
    blue = dice["blue"][randint(0, 5)]
    green = dice['green'][randint(0, 5)]

    winner = getWinner(red, blue, green)
    loser = getLoser(red, blue, green)

    results3Player[winner]['wins'] += 1
    results3Player[loser]['losses'] += 1

min = 0
max = 0

minDie = None
maxDie = None

for die in dice.keys():

    # Find the maximum winner and maximum loser

    if results3Player[die]['wins'] > max:
        max = results3Player[die]['wins']
        maxDie = die

    if results3Player[die]['losses'] > min:
        min = results3Player[die]['losses']
        minDie = die

print("The die most likely to win is %s with %.2f%% probability of winning" %(maxDie, max*100/rounds))
print("The die most likely to lose is %s with %.2f%% probability of losing" %(minDie, min*100/rounds))
这段代码有两部分我仍然不明白

def runGame(p1, p2):
    die1 = dice[p1]
    die2 = dice[p2]

    return 1 if die1[randint(0, 5)] > die2[randint(0, 5)] else 2
如果骰子1返回的数字介于0和5之间,大于骰子2返回的数字,则程序将返回1。如果不是,它将返回2。 在这种情况下,1和2是什么意思

然后是这一部分

for opponent in results.keys():

    remaining = list(dice.keys())
    remaining.remove(opponent)

    for player in remaining:
        wins = 0

        for _ in range(rounds):
            if runGame(player, opponent) == 1:
                wins += 1

        results[opponent][player] = wins / rounds

print("completed.")
如果我理解正确的话。剩余表示骰子字典中的值列表。当玩家和对手获胜时,字典中将添加一个新值。 但我不确定剩下的.removeOperator是什么意思。 以何种方式清除对手

在这种情况下,1和2是什么意思

1表示p1代表的玩家获胜,2表示p2代表的玩家获胜

但我不确定剩下的.removeOperator是什么意思。以何种方式清除对手

它只是从列表中删除。玩家剩余的循环:让这个对手和每个玩家玩一场游戏,而让一个玩家和自己玩是没有意义的。因此,我们首先从列表中删除该玩家

另一种方法是跳过循环中的玩家:

players = list(results.keys())
for player in players:
    for opponent in players:
        if player == opponent:
            continue # don't play against yourself
        wins = 0
        for _ in range(rounds):
            if runGame(player, opponent) == 1:
                wins += 1
        results[opponent][player] = wins/rounds