python 中的废话

发布于 2024-10-21 23:50:10 字数 1280 浏览 1 评论 0原文

我正在尝试模拟 n 场双骰子游戏。该代码对我来说似乎很有意义,但我从未得到正确的结果。例如,如果我输入 n = 5,即五场比赛,则胜利和失败的总和大于 5。

它的工作原理如下:如果初始掷骰子数为 2、3 或 12,则玩家失败。如果掷骰结果为 7 或 11,则玩家获胜。任何其他初始掷骰都会导致玩家再次掷骰。他继续掷骰,直到掷出 7 或初始掷骰的值。如果他在掷出 7 之前重新掷出初始值,则获胜。首先掷出 7 就输了。

from random import randrange

    def roll():
        dice = randrange(1,7) + randrange (1,7)
        return dice

    def sim_games(n):
        wins = losses = 0
        for i in range(n):
            if game():
                wins = wins + 1
            if not game():
                losses = losses + 1
        return wins, losses

    #simulate one game

    def game():

            dice = roll()
            if dice == 2 or dice == 3 or dice == 12:
                return False
            elif dice == 7 or dice == 11:
                return True
            else:
                dice1 = roll()
                while dice1 != 7 or dice1 != dice:
                    if dice1 == 7:
                        return False
                    elif dice1 == dice:
                        return True
                    else:
                        dice1 = roll()

    def main():

        n = eval(input("How many games of craps would you like to play? "))
        w, l = sim_games(n)

        print("wins:", w,"losses:", l)

I'm trying to simulate n games of craps. The code seems to make sense to me but I never get the right result. For example, if I put in n = 5 i.e. fives games the wins and losses sum to something greater than 5.

Here's how it's supposed to work: if initial roll is 2, 3, or 12, the player loses. If the roll is 7 or 11, the player wins. Any other initial roll causes the player to roll again. He keeps rolling until either he rolls a 7 or the value of the initial roll. If he re-rolls the initial value before rolling a 7, it's a win. Rolling a 7 first is a loss.

from random import randrange

    def roll():
        dice = randrange(1,7) + randrange (1,7)
        return dice

    def sim_games(n):
        wins = losses = 0
        for i in range(n):
            if game():
                wins = wins + 1
            if not game():
                losses = losses + 1
        return wins, losses

    #simulate one game

    def game():

            dice = roll()
            if dice == 2 or dice == 3 or dice == 12:
                return False
            elif dice == 7 or dice == 11:
                return True
            else:
                dice1 = roll()
                while dice1 != 7 or dice1 != dice:
                    if dice1 == 7:
                        return False
                    elif dice1 == dice:
                        return True
                    else:
                        dice1 = roll()

    def main():

        n = eval(input("How many games of craps would you like to play? "))
        w, l = sim_games(n)

        print("wins:", w,"losses:", l)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

_畞蕅 2024-10-28 23:50:10

问题在于 相反

        if game():
            wins = wins + 1
        if not game():
            losses = losses + 1

,它应该

        if game():
            wins = wins + 1
        else:
            losses = losses + 1

在您的代码中,您正在模拟两个游戏而不是一个(通过调用 game() 两次)。这给出了四种可能的结果,而不是两种(赢/输),从而给出了不一致的总体结果。

The problem is with

        if game():
            wins = wins + 1
        if not game():
            losses = losses + 1

Instead, it should be

        if game():
            wins = wins + 1
        else:
            losses = losses + 1

In your code, you are simulating two games instead of one (by calling game() twice). This gives four possible outcomes instead of two (win/loss), giving inconsistent overall results.

本宫微胖 2024-10-28 23:50:10

在此代码中,

for i in range(n):
    if game():
        wins = wins + 1
    if not game():
        losses = losses + 1

您调用了 game() 两次,因此您在那里玩了两个游戏。您想要的是 else 块:

for i in range(n):
    if game():
        wins = wins + 1
    else:
        losses = losses + 1

顺便说一句,您可以使用 in 简化逻辑:

def game():
    dice = roll()

    if dice in (2,3,12):
        return False

    if dice in (7,11):
        return True

    # keep rolling
    while True:
        new_roll = roll()

        # re-rolled the initial value => win
        if new_roll==dice:
            return True

        # rolled a 7 => loss
        if new_roll == 7:
            return False

        # neither won or lost, the while loop continues ..

代码实际上就是您给出的描述。

In this code

for i in range(n):
    if game():
        wins = wins + 1
    if not game():
        losses = losses + 1

you call game() twice, so you play two games right there. What you want is a else block:

for i in range(n):
    if game():
        wins = wins + 1
    else:
        losses = losses + 1

Btw, you can simplify the logic with in:

def game():
    dice = roll()

    if dice in (2,3,12):
        return False

    if dice in (7,11):
        return True

    # keep rolling
    while True:
        new_roll = roll()

        # re-rolled the initial value => win
        if new_roll==dice:
            return True

        # rolled a 7 => loss
        if new_roll == 7:
            return False

        # neither won or lost, the while loop continues ..

The code is quite literally the description you gave.

还给你自由 2024-10-28 23:50:10

不要这样做,

    for i in range(n):
        if game():
            wins = wins + 1
        if not game():
            losses = losses + 1

效果根本不好。

Don't do this

    for i in range(n):
        if game():
            wins = wins + 1
        if not game():
            losses = losses + 1

It doesn't work out well at all.

倾城花音 2024-10-28 23:50:10

这段代码有很多问题。最重要的是,每个循环都会调用 game() 两次。您需要调用它一次并存储结果,然后基于该结果进行切换。

There are numerous problems with this code. Most importantly, you're calling game() twice per loop. You need to call it once and store the result, and switch based on that.

嘿哥们儿 2024-10-28 23:50:10

面向对象的重写:

import random

try:
    rng = xrange   # Python 2.x
    inp = raw_input
except NameError:
    rng = range    # Python 3.x
    inp = input

def makeNSidedDie(n):
    _ri = random.randint
    return lambda: _ri(1,n)

class Craps(object):
    def __init__(self):
        super(Craps,self).__init__()
        self.die = makeNSidedDie(6)
        self.firstRes = (0, 0, self.lose, self.lose, 0, 0, 0, self.win, 0, 0, 0, self.win, self.lose)
        self.reset()

    def reset(self):
        self.wins   = 0
        self.losses = 0

    def win(self):
        self.wins += 1
        return True

    def lose(self):
        self.losses += 1
        return False

    def roll(self):
        return self.die() + self.die()

    def play(self):
        first = self.roll()
        res   = self.firstRes[first]
        if res:
            return res()
        else:
            while True:
                second = self.roll()
                if second==7:
                    return self.lose()
                elif second==first:
                    return self.win()

    def times(self, n):
        wins = sum(self.play() for i in rng(n))
        return wins, n-wins

def main():
    c = Craps()

    while True:
        n = int(inp("How many rounds of craps would you like to play? (0 to quit) "))
        if n:
            print("Won {0}, lost {1}".format(*(c.times(n))))
        else:
            break

    print("Total: {0} wins, {1} losses".format(c.wins, c.losses))

if __name__=="__main__":
    main()

An OO rewrite:

import random

try:
    rng = xrange   # Python 2.x
    inp = raw_input
except NameError:
    rng = range    # Python 3.x
    inp = input

def makeNSidedDie(n):
    _ri = random.randint
    return lambda: _ri(1,n)

class Craps(object):
    def __init__(self):
        super(Craps,self).__init__()
        self.die = makeNSidedDie(6)
        self.firstRes = (0, 0, self.lose, self.lose, 0, 0, 0, self.win, 0, 0, 0, self.win, self.lose)
        self.reset()

    def reset(self):
        self.wins   = 0
        self.losses = 0

    def win(self):
        self.wins += 1
        return True

    def lose(self):
        self.losses += 1
        return False

    def roll(self):
        return self.die() + self.die()

    def play(self):
        first = self.roll()
        res   = self.firstRes[first]
        if res:
            return res()
        else:
            while True:
                second = self.roll()
                if second==7:
                    return self.lose()
                elif second==first:
                    return self.win()

    def times(self, n):
        wins = sum(self.play() for i in rng(n))
        return wins, n-wins

def main():
    c = Craps()

    while True:
        n = int(inp("How many rounds of craps would you like to play? (0 to quit) "))
        if n:
            print("Won {0}, lost {1}".format(*(c.times(n))))
        else:
            break

    print("Total: {0} wins, {1} losses".format(c.wins, c.losses))

if __name__=="__main__":
    main()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文