Python,Decode the Morse code, advanced

# Decode the Morse code, advanced
# https://www.codewars.com/kata/54b72c16cd7f5154e9000457/train/python

def decode_bits(bits):
    bits = bits.strip('0')
    times = 1
    #找出扩大倍数, 也就是所有的连续1和连续0的长度的最小值
    #bits.split('0')|bits.split('1')是将bits按照0或者1分割,然后取并集, if x是过滤掉空字符串
    times = min([len(x) for x in set(bits.split('0'))|set(bits.split('1')) if x])
    if(times > 1):
        bits = bits.replace('1'*times,'1').replace('0'*times,'0')
    return bits.replace('111', '-').replace('1', '.').replace('0000000','   ').replace('000', ' ').replace('0', '')

def decode_morse(morseCode):
    return ' '.join(''.join([MORSE_CODE[letter] for letter in word.split(' ')]) for word in morseCode.strip().split('   '))

# 1 0 1 0 1 0 1 000   1 000   111   0 1 0 111   0 111   0000000       1 0 111   0 111   0 111   000   1 0 1 0 111   000   111   0 1 0 1 000   1
# 1100110011001100000011000000111111001100111111001111110000000000000011001111110011111100111111000000110011001111110000001111110011001100000011



# best practice
def decodeBits(bits):
    import re
    
    # remove trailing and leading 0's
    bits = bits.strip('0')
    
    #找出扩大倍数, 也就是所有的连续1和连续0的长度的最小值
    # re是python的正则表达式模块
    # re.findall(pattern,string,flags=0) 返回一个列表,其中包含字符串中所有与模式匹配的子串
    # r'1+|0+'是正则表达式,表示匹配连续的1或者连续的0
    # '1'匹配字符1,'1+'匹配1个或多个1,
    # '|'表示或者, 连接两个表达式, 满足其中一个就匹配成功
    # '0'匹配字符0,'0+'匹配1个或多个0
    # r或R是python的原始字符串标识符,加在字符串之前使一个字符串成为原始字符串
    # 原始字符串中的反斜杠'\'不会被解释为转移字符,而是作为普通字符,
    # 原始字符串对于处理正则表达式或文件路径等包含大量反斜杠的字符串非常有用
    time_unit = min(len(m) for m in re.findall(r'1+|0+', bits))
    
    # ::是python的切片操作符, [start:end:step]
    # [::time_unit]表示从0开始,到结束,每隔time_unit取一个元素,组成一个新的字符串
    # a = '1234567890'
    # print(a[::2])#13579
    return bits[::time_unit].replace('111', '-').replace('1','.').replace('0000000','   ').replace('000',' ').replace('0','')

def decodeMorse(morseCode):
    return ' '.join(''.join(MORSE_CODE[l] for l in w.split()) for w in morseCode.split('   '))
posted @ 2025-03-25 15:14  Kazuma_124  阅读(39)  评论(0)    收藏  举报