编程笔试2020221

题目:

一个字符串, 当其中出现超过2个的连续字符时候,将其改写成该字符的数字+该字符。例如'aaaabbcd',改写成‘4abbcd’。

请写一个unzip函数,判断输入的字符串是否符合该改写规则,如果符合,打印原始字符串。

注意:使用left变量传递参数。判断每个字符的前一位是否为数字。

s='10abb4c51d'

def unzip(s):
    left=0
    output=[]
    for i in range(len(s)):
        c=ord(s[i])
        if c>=97 and left==0:#是字母,且左边不是数字
            output.append(s[i])
        if c>=97 and left>2:
            output.append(s[i]*left)
        #print(s[i]*left,end='')#是字母,左边数字>2
            left=0
        if c>=97 and (left ==1 or left==2): #是字母,左边数字是1或2
            return False
        if c<97: #是数字
            left=left*10+int(s[i]) # 是数字
        if i==len(s)-1 and c<97:
            return False
    return output

result=unzip(s)
if not result:
    print('!error')
else:
    for ele in result:
        print(ele,end='')
发布了163 篇原创文章 · 获赞 90 · 访问量 6259

猜你喜欢

转载自blog.csdn.net/weixin_45405128/article/details/104426836
今日推荐