编写一个程序,该程序生成20次随机掷骰的序列,并打印出掷骰值,仅标记最长的运行时间

时间:2019-11-12 20:31:45

标签: python python-3.x

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)622165213363

我很难标出最长的跑步次数,而不是标出相同的相邻数字。

[edit]感谢大家的解决方案!要基于此代码,如何返回最长运行的索引?

2 个答案:

答案 0 :(得分:1)

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

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

使用该功能,我们可以追踪最长的跑步时间。尝试以下代码:

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

inRun = False

#count the run lenght
run = ""
for i in range(len(L)):
    if inRun:
        if L[i] != L[i-1]:
            # add the last run we have collected during the loop
            runs.append(run)



            # research for more runs
            run = ""
            inRun = False
            continue
        else:
            run += str(L[i])


    if not inRun:
        if i != len(L)-1:
            if L[i] == L[i+1]:
                run += str(L[i])

                inRun = True


print("\n")

#sort runs so the longest run is in index -1 (last)
# key=len means we sort by len

runs = sorted(runs, key=len)
# create a new string variable holding our list so we could use replace function
# we must use the string value of every int using str(x)
result = ""


if (len(runs) > 0):
    result = result.join(str(x) for x in L)

    #replacing the run with the same value but with "()"
    result = result.replace(runs[-1], "(" + runs[-1] + ")" , 1) # use 1 to tell python not mark more than one run if possible



print(result)

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

答案 1 :(得分:0)

您非常接近。用于分组的开/关开关的逻辑工作不正确。考虑创建子组和一个跟踪最长的子组的变量。然后,对子组进行迭代,并在长度正确(最长)的子组周围添加括号。

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]的示例,您将看到以下内容:

groups
# returns:
[[4],
 [5],
 [2],
 [6, 6],
 [5, 5, 5],
 [6],
 [2, 2],
 [1],
 [6],
 [5],
 [2],
 [1],
 [3, 3],
 [6]]

# printed output:
45266(555)62216521336