Python,codewars,Strings Mix,5629db57620258aa9d000014

# Strings Mix
# https://www.codewars.com/kata/5629db57620258aa9d000014

def mix(s1, s2):
    s1 = ''.join([c for c in s1 if c.islower()])
    # [c for c in s1 if c.islower()] 为 s1 中的小写字母组成的列表
    # ''.join(x), x 为列表,将列表中的元素用''连接成字符串
    s2 = ''.join([c for c in s2 if c.islower()])
    s1 = {c: s1.count(c) for c in set(s1)}
    s2 = {c: s2.count(c) for c in set(s2)}
    s = []
    for c in set(s1.keys()) | set(s2.keys()):# set(s1.keys()) | set(s2.keys()) 为 s1 和 s2 的并集
        if c in s1 and c in s2 and max(s1[c], s2[c]) > 1:
            if s1[c] > s2[c]:
                s.append('1:' + c * s1[c])
            elif s1[c] < s2[c]:
                s.append('2:' + c * s2[c])
            else:
                s.append('=:' + c * s1[c])
        elif c in s1 and s1[c] > 1:
            s.append('1:' + c * s1[c])
        elif c in s2 and s2[c] > 1:
            s.append('2:' + c * s2[c])
    s.sort(key=lambda x: (-len(x), x)) # 首先按照 -len(x) 升序(即长度降序),然后按照 x 升序
    return '/'.join(s)

print(mix("Are they here", "yes, they are here"), "2:eeeee/2:yy/=:hh/=:rr")

def mix_2(s1,s2):
    s1 = ''.join([ch for ch in s1 if ch.islower()])
    s2 = ''.join([ch for ch in s2 if ch.islower()])
    s1 = {ch: s1.count(ch) for ch in set(s1)}
    s2 = {ch: s2.count(ch) for ch in set(s2)}
    results = []
    for ch in set(s1.keys()) | set(s2.keys()):
        if ch in s1 and ch in s1 and max(s1[ch],s2[ch])>1:
            if s1[ch]>s2[ch]:
                results.append('1:'+ch*s1[ch])
            elif s1[ch]<s2[ch]:
                results.append('2:'+ch*s2[ch])
            else:
                results.append('=:'+ch*s1[ch])
        elif ch in s1 and s1[ch]>1:
            results.append('1:'+ch*s1[ch])
        elif ch in s2 and s2[ch]>1:
            results.append('2:'+ch*s2[ch])
    results.sort(key = lambda x : (-len(x),x))
    return '/'.join(results)
posted @ 2025-03-07 20:32  Kazuma_124  阅读(9)  评论(0)    收藏  举报