应该是一卷骰子(随机),然后相邻的值(游程)应该位于()中。一个挑战是使用当前的-索引为0的数字(想想我是通过使用range(len(dieRun)-1来解决的)。但是另一个挑战是使用“ current + 1”,因为它倾向于“超出范围”错误
我想到的一个可能是构建一个函数以比较相邻元素的值?然后使用从中获得的任何回报引用一个变量,然后在dieRun的格式化Print中使用该变量?但是,我看不出会有什么更好的选择,因为那样的话,我仍然不得不弄清楚如何使用print(dieRun)列表将变量作为“(”或“)”放置。 还是个新手。
def main():
from random import randint
counter = 0
inRun = 0
dieRun = []
while counter < 20:
roll = randint(0,6)
dieRun.append(roll)
counter = counter +1
index = 0
counter = 0
value = 0
inRun == False
print(dieRun) # just to see what I'm working with
while counter < len(dieRun):
for i in range(0, len(dieRun)-1):
if dieRun[i] != dieRun[i-1]:
print(")" , end= "")
inRun = False
counter = counter + 1
if dieRun[i] == dieRun[i+1]:
inRun = True
print("(")
counter = counter + 1
print(dieRun[i])
if inRun:
print("(")
if inRun :
print(")", end="")
main()
答案 0 :(得分:0)
如果您希望输出如下:1(3 3)4 5(6 6 6)2 1 3(2 2)1(4 4)5 6 1 2
from random import randint
dieRun = []
for i in range(20):
roll = randint(0,6)
dieRun.append(roll)
inRun = False
print(dieRun)
for i, n in enumerate(dieRun):
if i < len(dieRun)-1:
if not inRun:
if n == dieRun[i+1]:
print('(', n,' ', end='')
inRun = True
else:
print(n,' ', end='')
else:
if n != dieRun[i+1]:
print(n, ')',' ', end='')
inRun = False
else:
print(n,' ', end='')
else:
if dieRun[i-1] == n:
print(n, ')')
else:
print(n)
只是一个想法,希望对您有所帮助。
答案 1 :(得分:-1)
快速修复,我已经在代码中添加了注释。
对于嵌入式打印,您已经提供了解决方案'print(“)”,end =“”))',但是我不知道为什么您没有为每个print()都使用它。
if dieRun[i] != dieRun[i-1]: # will check the first number with last number
dieRun[0] != dieRun[-1]: # [-1] is the last item in the list
if dieRun[i] == dieRun[i+1]: # will index out of length
dieRun[len(..)-1] != dieRun[len(..)]: # [len(..)] wil be out of range
由于列表的开头和结尾总是会引起问题,因此我只是将它们从for循环中删除,然后手动进行。
必须有一些更清洁的解决方案:
from random import randint
counter = 0
inRun = 0
dieRun = []
while counter < 20:
roll = randint(0,6)
dieRun.append(roll)
counter = counter +1
index = 0
counter = 0
value = 0
inRun == False
print(dieRun)
# while counter < len(dieRun): # while loop is redundant with the for loop
print('(', dieRun[0],' ', end='') # print the first number manually
for i in range(1, len(dieRun)-1):
if dieRun[i] != dieRun[i-1]:
print(")(" , end= "") # change ")" to ")("
inRun = False
counter = counter + 1
"""
these are redundant, just like if True, don't need elif not True
# if dieRun[i] == dieRun[i+1]:
# inRun == True
# print("(", end='')
# counter = counter + 1
"""
print(dieRun[i],' ', end='')
print(dieRun[-1],')', end='') # print the last number manually