写一个程序,生成20个随机掷骰子的序列,并打印模具值,只标记最长的一次

2024-04-26 21:36:01 发布

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

import random
L = [random.randrange(1, 7) for i in range(20)]
print(L)

inRun = False

for i in range(len(L)):
    if inRun:
        if L[i] != L[i-1]:
            print (')', end = '')
            inRun = False
    if not inRun:
        if i != len(L)-1:
            if L[i] == L[i+1]:
                print('(', end = '')
                inRun = True
    print(L[i], end = '')

if inRun:
    print(')', end = '') 

输入列表:[4,5,2,6,6,5,5,5,6,2,2,1,6,5,2,1,3,3,6,3]

输出:452(66)(555)6(22)16521(33)63
应输出:45266(555)62216521363

我在标记最长距离时遇到了问题,而不是标记相邻的每个相同的数字。在

[编辑]谢谢大家的解决方案!在这段代码的基础上,如何返回最长运行时间的索引?在


Tags: in标记importfalsetrueforlenif
2条回答

你已经很接近了。分组的开/关开关的逻辑不太正确。考虑创建子组和一个变量来跟踪所看到的最长的一个。然后迭代子群,并在长度正确(最长)的子群周围添加paren。在

import random

L = [random.randrange(1, 7) for i in range(20)]
groups = []
current_run = []
longest_run = 0
for x in L:
    if (not current_run) or (x == current_run[-1]):
        current_run.append(x)
        if longest_run < len(current_run):
            longest_run += 1
    else:
        groups.append(current_run)
        current_run = [x]

for g in groups:
    g_str = ''.join(map(str, g))
    if len(g) == longest_run:
        print(f'({g_str})', end='')
    else:
        print(g_str, end='')

对于L = [4, 5, 2, 6, 6, 5, 5, 5, 6, 2, 2, 1, 6, 5, 2, 1, 3, 3, 6, 3]的示例,您将看到以下内容:

^{pr2}$

你的代码的问题是你标记了每一次运行的数字。我建议你运行你的循环,然后用括号编辑它。因此,在标记每个跑步记录之前,您需要存储所有跑步记录,然后选择最长的跑步记录。我建议使用名为sorted的内置函数:

L = ["99", "888", "1"]
print(sorted(L, key=len))

使用该功能,我们可以跟踪最长的跑步记录。请尝试以下代码:

^{pr2}$

请告诉我它是否解决了你的问题。 一切顺利

相关问题 更多 >