1

我只是在学习 Python(有史以来的第一门语言),并且正在以我觉得有趣的方式实现我发现的东西。我建立了一个伪老虎机赔率计算器。然而,它止于一次大奖的胜利。有没有办法让它一遍又一遍地运行,以给出 n 场比赛的平均尝试次数以获得大奖?

这是我的代码

#!/usr/bin/env python
import random

a = 1

while a >0 :
    l1 = random.randrange(36)
    l2 = random.randrange(36)
    l3 = random.randrange(36)

    print l1, l2, l3
    if l1 == l2 == l3 == 7:
        print 'grand prize winner!!!'
        break
    elif l1 == l2 == l3:
        print 'you won! congratulations'
        print 'it took', a, 'attempts to win'
    else:
        a += 1
        print 'sorry...  try again'
        print 'attempt', a

另外,有没有办法告诉我在赢得大奖的过程中有多少正常的胜利

4

4 回答 4

2

break大奖块中的语句if退出外while循环。如果您希望它继续运行,请删除break. 另外,作为一个风格点,while True:或者while 1:是一个更清晰的创建无限循环的方法。至于问题的第二部分,您有a计数器,但您可能想要捕获更多数据,如下所示:

import random

def play(till_jackpot_count):
    game_data_per_jackpot = [{'plays' : 0, 'wins' : 0}]
    wheel_values = xrange(36)
    wheels = [0, 0, 0]
    while till_jackpot_count >= len(game_data_per_jackpot):
        wheels = [random.choice(wheel_values) for wheel in wheels]
        game_data_per_jackpot[-1]['plays'] += 1
        print '%d plays since last jackpot' % game_data_per_jackpot[-1]['plays']
        print '%d wins since last jackpot' % game_data_per_jackpot[-1]['wins']
        print '%d total plays' % sum([data['plays'] for data in game_data_per_jackpot])
        print '%d total wins' % sum([data['wins'] for data in game_data_per_jackpot])
        print '%d total jackpots' % (len(game_data_per_jackpot) - 1)
        print 'this play: {} {} {}'.format(*wheels)
        if len(set(wheels)) == 1:
            if wheels[0] == 7:
                print 'jackpot!'
                game_data_per_jackpot.append({'plays' : 0, 'wins' : 0})
            else:
                print 'win!'
                game_data_per_jackpot[-1]['wins'] += 1
    return game_data_per_jackpot[:-1]

play(10)

我还在顶部偷偷插入了一个控件,该控件till_jackpot_count将在该数量的累积奖金之后结束循环。如果您想在函数本身之外进一步分析测试结果,该函数还会返回测试结果,但结果只是被丢弃在这里,因为它没有分配给任何东西。

为了您自己的学习,这段代码使用了列表[](除了您已经熟悉的库和循环。我还把你的换成了一个更简单、可能更高效的预建.{}()'%d' % var'{} {} {}'.format(*iterable)[a for a in b]list[:]sumlenrandomwhilerandom.randrange()random.sample()xrange()

于 2012-09-27T16:57:45.963 回答
0

您只需要计算每次获胜的次数,然后在最后打印总数......(见wins下文)

#!/usr/bin/env python
import random
def play():
  a = 1
  wins = 0
  while a >0 :
    l1 = random.randrange(36)
    l2 = random.randrange(36)
    l3 = random.randrange(36)

    print l1, l2, l3
    if l1 == l2 == l3 == 7:
        #print 'grand prize winner!!!'
        break
    elif l1 == l2 == l3:
        #print 'you won! congratulations'
        #print 'it took', a, 'attempts to win'
        wins += 1
    else:
        a += 1
        print 'sorry...  try again'
        print 'attempt', a
  return a,wins
  #print "You Won %s Times!"%wins

play_again = True
while play_again:
    tries,wins = play()
    print "It Took %d Tries to win the Grand Prize"%tries
    print "You won normally %d Times"%wins
    play_again = raw_input("Play Again(y/n)?")==y
于 2012-09-27T17:02:57.583 回答
0

要运行一些代码n时间,您应该编写

for _ in range(n):
    # some code

要在某些条件成立时运行它,您应该编写

while condition:
    #some code

要无限运行它,你应该写

while 1:
     # some code

(因为条件1始终为真)。

break即使条件不成立,关键字也会让您跳出循环。


首先设置老虎机代码:

GRAND_PRIZE = 0
REGULAR_PRIZE = 1
NO_PRIZE = 2

def slot_machine():
    l1 = random.randrange(36)
    l2 = random.randrange(36)
    l3 = random.randrange(36)

    if l1 == l2 == l3:
        return GRAND_PRIZE if l1 == 7 else REGULAR_PRIZE
    else:
        return NO_PRIZE

接下来,设置代码以运行它,直到您获胜。

def run_until_win():
    num_tries = 0
    num_wins = 0

    while 1:
        num_tries += 1
        result = slot_machine()

        if result == GRAND_PRIZE:
            break
        elif result == REGULAR_PRIZE:
            num_wins += 1

    return num_tries, num_wins

最后,运行十次:

for _ in range(10):
    print "tries: {0}, wins: {1}".format(*run_until_win())
于 2012-09-27T17:10:36.163 回答
0

您的“while”循环没有任何问题,它应该逃逸。现在,如果你想多次运行它,你可以将它包装在一个for i in range(number_of_games)循环中。每次退出while循环时,都会将 附加a到列表中。

nb_attempts = []
for i in range(nb_games):
    while True:
        ...
        if (l1 == l2 == l3 == 7):
            nb_attempts.append(a)
            break
        elif ...

在你的n游戏结束时,你有一个尝试次数列表n。尝试次数。

于 2012-09-27T17:13:06.860 回答