我有一个分配,我必须编写一个算法,生成所选r整数的Conway序列的l行。 l = 8且r = 1的示例:
1
1 1
2 1
1 2 1 1
1 1 1 2 2 1
3 1 2 2 1 1
1 3 1 1 2 2 2 1
1 1 1 3 2 1 3 2 1 1
我曾尝试在Python3中编写算法,但我无法获得正确的输出。如果你能帮我弄清楚什么是错的,我会很感激......无论如何,这是我到目前为止写的:
r = int(input())
l = int(input())
cur=str(r).strip()
print(r)
for j in range(l-1):
r=cur
cur=""
i=0
while i<len(r) :
c=1 #counts the consecutive same "numbers"
while ((i+c*2)<len(r)) and (r[i]==r[i+c*2]):
c+=1
cur+=str(c)+" "+r[i]+" "
i+=c+1
cur=cur.strip()
print(cur)
这是我得到的输出l = 8和r = 1:
1
1 1
2 1
1 2 1 1
1 1 1 2 2 1
3 1 1 1 2 2 1
1 3 3 1 1 1 2 2 1
1 1 2 3 6 2 2 1
我也觉得我的代码非常难看,所以随时发表评论
答案 0 :(得分:0)
看看这个逻辑, 我从以下代码获得:HERE
r = [input()]
l = int(input())
# Write an answer using print
# To debug: print("Debug messages...", file=sys.stderr, flush=True)
for i in range(l - 1):
temp = list()
lastChar = r[0]
counter = 0
for char in r:
if lastChar == char:
counter += 1
else:
temp.extend([str(counter), lastChar])
lastChar = char
counter = 1
temp.extend([str(counter), lastChar])
r = temp
print(r)
print(" ".join(r))