20次抛模随机模拟

2024-10-03 17:24:04 发布

您现在位置:Python中文网/ 问答频道 /正文

尝试随机模拟20个掷骰子,代码需要用括号括起一个相同的值,括号出现,但我的公式中缺少一些东西,任何建议都会有很大帮助,例如:

1 ( 4 1 ) 2 3 6 1 4 3 2 6 6 6 5 6 2 1 3 5 3 # incorrect
1 4 1 2 3 6 1 4 3 2 ( 6 6 6 ) 5 6 2 1 3 5 3 # this is a correct example 
def main():

    exampleList = [ ]

    for i in range(20):
        exampleList.append(randint(1, 6))
    print(exampleList)
    print(list(range(0,20)))

    max_count = 0
    run_count = 0

    matched = False #inRun = False           
    # find max run
    for rollValue in exampleList:
      #print(rollValue)
      if run_count == 19:
          print()

      else:          
          print("-------")
          print("Roll Value %s" % exampleList[run_count])
          print("Position   %s" % run_count)
          print("Next Roll value %s" % exampleList[run_count + 1])
          if exampleList[run_count] == exampleList[run_count + 1]:
             matched = True
             print("------->>>matched")
          else:
             matched = False#inRun = False
          run_count += 1

      if rollValue < 19:
          if exampleList[rollValue] == exampleList[rollValue + 1]:
             run_count += 1
          if matched == False:
              matched == True
              run_count = rollValue

          else:
            matched = False
          if run_count > max_count:
             run_count = 1
    # print sequence
    for rollValue in range(20):
       if rollValue == run_count:
               print("(", exampleList[rollValue], end = " ")

       elif rollValue == run_count + max_count + 1:
            print(exampleList[rollValue], ")", end = " ")

       else:
            print(exampleList[rollValue], end = " ")            
main()

Tags: runinfalseforifcountrangeelse
3条回答

你的代码有很多问题,所以重写整个代码会更快。你知道吗

def main():
    example_list = []
    for _ in range(20):
        example_list.append(random.randint(1, 6))

    inside = False
    for index in range(len(example_list)):

        try:
            if inside:
                if example_list[index] != example_list[index + 1]:
                    print("%d )" % example_list[index], end=" ")
                    inside = False
                else:
                    print(example_list[index], end=" ")
            else:
                if example_list[index] == example_list[index + 1]:
                    print("( %d" % example_list[index], end=" ")
                    inside = True
                else:
                    print(example_list[index], end=" ")
        except IndexError:
            print("%d" % example_list[index], end=" ")

            if inside:
                print(")")
            else:
                print()

正如你所看到的,我通过使用一个变量来跟踪我是否在括号内。我看下一个数字来猜是否应该加一个右括号。你知道吗

最后一个案子由审判员处理。你知道吗

你也可以通过向前看和向后看来处理每个数字,但是这需要你为try-except部分添加一些额外的条件,所以这只是

下面是一个使用regex的解决方案。这将从骰子卷中创建一个字符串,然后查找重复的数字并使用^{}添加括号。你知道吗

import re
import random

rolls = ''.join(map(str, [random.choice(range(1, 7)) for _ in range(20)]))
rolls = ' '.join(re.sub(r'(\d)(\1+)', r'(\1\2)', rolls))
print(rolls)

几个示例运行:

4 1 4 3 4 6 5 2 3 ( 5 5 ) 1 6 4 3 5 2 5 ( 4 4 )
2 ( 1 1 ) 4 1 ( 5 5 ) ( 3 3 ) 6 2 ( 1 1 ) 5 1 4 3 4 ( 5 5 )

正则表达式解释:

(                             // start of matching group 1
  \d                          // matches a single digit
)                             // end of matching group 1
(                             // start of matching group 2
  \1+                         // matches group 1, 1 or more times
)                             // end of matching group 2

这将添加括号作为列表的一部分:

#!/usr/bin/python

import sys
from random import randint


# add parenthesis as part of the list
def main():

    exampleList = [ ]
    previous = -1
    opened = False

    for i in range(20):
        roll = randint(1, 6)
        if roll == previous:
            if not opened:
                exampleList.insert(-1, '(')
                opened = True
        else:
            if opened:
                exampleList.append(')')
                opened = False
        exampleList.append(roll)
        previous = roll
    if opened:
        exampleList.append(')')
    for item in exampleList:
        sys.stdout.write('{0} '.format(item))
    sys.stdout.write('\n')


if __name__ == '__main__':
    main()

示例:

( 2 2 ) 4 5 1 2 1 ( 6 6 ) 1 6 1 4 1 ( 6 6 ) 1 6 2 4 
2 ( 6 6 ) ( 1 1 ) 3 2 1 ( 4 4 ) 1 2 5 4 1 5 3 ( 5 5 5 )

相关问题 更多 >