尝试以特定方式对字母字符进行排序,但不能完全正确



https://www.codingame.com/上有一个谜题,我一直试图弄清楚一段时间。您已以特定格式对一组特定的字母进行排序。假设输入是:

缩写

那么输出将是:

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)

现在这有效,直到我到达最后一组字符。例如,如果我输入:

缩写

我会得到:

1a2b3c

无论我怎么尝试,我都无法获得最后一个数字和字符,有什么想法吗?

你不应该存储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)

最新更新