https://www.codingame.com/上有一个谜题,我一直想弄清楚。您已按特定格式对特定字母组进行排序。说输入是:
abbcccdddd
然后输出将是:
1a2b3c4d
这是我的代码:
s = input()
lstr = list(s)
hold = []
fullstr = ''
for c in lstr:
if len(hold) == 0:
hold.append(c)
elif c == hold[len(hold) - 1] and c != lstr[len(lstr) - 1]:
hold.append(c)
elif c != hold[len(hold) - 1]:
fullstr += str(len(hold))
fullstr += str(hold[len(hold)-1])
hold[:] = []
hold.append(c)
if c == lstr[len(lstr) - 1]:
break
print(fullstr)
现在这个工作,直到我到达最后一组字符。例如,如果我输入:
,我将使用上面的相同示例abbcccdddd
我会得到:
1a2b3c
无论我尝试什么,我都无法获得最后的数字和角色,任何想法?
答案 0 :(得分:0)
你不应该存储n次相同的字符,只需增加一个int
s = input()
lstr = list(s)
current = ''
nb_current = 0
fullstr = ''
for c in lstr:
if nb_current ==0: #only for the first character of the list
current = c
nb_current = 1
elif c==current:
nb_current += 1
else:
fullstr += str(nb_current)
fullstr += current
current = c
nb_current = 1
if nb_current>0:
fullstr += str(nb_current)
fullstr += current
print(fullstr)