# 欣赏一个简洁利落的解法

s1 = "my&friend&Paul has heavy hats! &"

s2 = "my friend John has many many friends &"

mix(s1, s2) --> "2:nnnnn/1:aaaa/1:hhh/2:mmm/2:yyy/2:dd/2:ff/2:ii/2:rr/=:ee/=:ss"

`from collections import Counterdef mix(s1, s2): c1 = Counter(filter(str.islower, s1)) c2 = Counter(filter(str.islower, s2)) res = [] for c in set(c1.keys() + c2.keys()): n1, n2 = c1.get(c, 0), c2.get(c, 0) if n1 > 1 or n2 > 1: res.append(('1', c, n1) if n1 > n2 else ('2', c, n2) if n2 > n1 else ('=', c, n1)) res = ['{}:{}'.format(i, c * n) for i, c, n in res] return '/'.join(sorted(res, key=lambda s: (-len(s), s)))`

解析：

1. filter:

filter(function, sequence)对sequence中的item依次执行function(item)，将执行结果为True的item组成一个List/String/Tuple（取决于sequence的类型）返回。

'myfriendaulhasheavyhats'

2. Counter:

Counter类的目的是用来跟踪值出现的次数。它是一个无序的容器类型，以字典的键值对形式存储，其中元素作为key，其计数作为value。

Counter(filter(str.islower, s1))的结果为：

{'a': 4, 'h': 3, 'e': 2, 's': 2, 'y': 2, 'd': 1, 'f': 1, 'i': 1, 'm': 1, 'l': 1, 'n': 1, 'r': 1, 'u': 1, 't': 1, 'v': 1}

3. 合并遍历2个字典:

for c in set(c1.keys() + c2.keys()):

4. 根据tuple合成一个字符串列表:

res = ['{}:{}'.format(i, c * n) for i, c, n in res]

5. 多重排序:

sorted(res, key=lambda s: (-len(s), s))

Top