首页 > 解决方案 > 想在相同的比赛后打印额外的字符,在这种情况下只有“s”

问题描述

仅在匹配后从以下字符串中打印's',例如: things 和 night 具有相同的字符串和 s 是额外的,需要打印到控制台

s1 = 'things'
s1 = sorted(s1)
s2 = 'night'
s2 = sorted(s2)

l1 = len(s1)
l2 = len(s2)

max_len = max(l1,l2)
# max_len = list(map(int, str(max_len)))

if s1[0:] != s2[0:]:
  for i in range(max_len):
    if s1[i] == s2[i]:
      print(s1[i])

预期输出:=s

标签: python

解决方案


您可以做一些Counter不同的事情来获取任一字符串中但不在另一个字符串中的所有字符:

from collections import Counter

def diff(s1, s2):
    c1, c2 = Counter(s1), Counter(s2)
    return "".join(((c1-c2) + (c2-c1)).elements())
    
diff("things", "night")
# 's'
diff("abcd", "cdef")
# 'abef'

一种更简单的方法,使用生成器:

def diff(s1, s2):
    for c in s1: 
        if c not in s2:
            yield c
    for c in s2: 
        if c not in s1:
            yield c

[*diff("things", "night")]
# ['s']
[*diff("abcd", "cdef")]
# ['a', 'b', 'e', 'f']

然而,这将忽略相同字符的不同计数。


推荐阅读