“伯爵说”序列如下:1,11,21,1211,111221, …。其1读作one 1或者11。11读作two 1s或者21。21读作one 2, one 1或者1211。
输入格式
多组输入,读到文件结束。每组输入给定一个整数 n(1≤n≤30)。
输出格式
输出第 n 个序列。注意,整数序列以字符串的形式表示。
样例输入
6
样例输出
312211
花了很长时间做出来,思路一直不对,在网上也没找的很好的解法。思路在下面
try:
while True:
x = int(input())
A = [1]
b = 0
B = []
C = []
if x > 1:
for j in range(x-1):
for i in A:
try:
if B[b] == i:
C[b] = C[b] + 1
else:
b = b + 1
B.append(i)
C.append(1)
except SyntaxError:
pass
except IndexError:
B.append(i)
C.append(1)
A = []
b = 0
for g, h in zip(C, B):
A.append(str(g))
A.append(str(h))
B = []
C = []
print("".join(A))
A = [1]
b = 0
B = []
C = []
else:
print('1')
A = [1]
b = 0
B = []
C = []
except EOFError:
pass
做出来后又花了一会时间试着用函数了写出来。
def Ji_Shu(up_list): # 计数函数,元素存入val__A,次数存入count_A。
new_val = 0
val__A = []
count_A = []
for i in up_list:
try: # 尝试判断新取出的元素是不是和之前的一样,出错就会跳到第二个except。
if val__A[new_val] == i: #count_A计相同元素个数
count_A[new_val] = count_A[new_val] + 1
else: #把新元素添加到val__A,并count_A也添加 1
new_val = new_val + 1
val__A.append(i)
count_A.append(1)
except SyntaxError: # 暂时没找到能去掉报错这一步的办法
pass
except IndexError: #把新元素添加到val__A,并count_A也添加 1
val__A.append(i)
count_A.append(1)
return val__A, count_A
def Shu_Shu(val__A, count_A): # 数数函数,结果存入up_list
up_list = []
for a, b in zip(count_A, val__A):
up_list.append(str(a))
up_list.append(str(b))
return up_list
def main():
try: # 判断是否空字符
while True:
x = int(input())
up_list = [1]
if x == 1:
print('1')
else:
for j in range(x-1):
val__A, count_A = Ji_Shu(up_list)
up_list = Shu_Shu(val__A, count_A)
print("".join(up_list))
except EOFError:
pass
if __name__ == '__main__':
main()