查找两个字符串之间的常用字符



我正在尝试使用for循环打印来自两个不同用户输入的常用字母。(我需要使用 for 循环来做到这一点。我遇到了两个问题:1.我的陈述"如果字符不在输出中......"不拉取唯一值。2.输出给了我一个单个字母的列表,而不是一个字符串。 我尝试拆分输出,但拆分遇到类型错误。

wrd = 'one'
sec_wrd = 'toe'
def unique_letters(x): 
output =[]
for char in x: 
if char not in output and char != " ": 
output.append(char)
return output
final_output = (unique_letters(wrd) + unique_letters(sec_wrd))
print(sorted(final_output))

您正在尝试执行设置交集。Python有set.intersection相同的方法。您可以将其用于您的用例,例如:

>>> word_1 = 'one'
>>> word_2 = 'toe'
#    v join the intersection of `set`s to get back the string
#    v                             v  No need to type-cast it to `set`.
#    v                             v  Python takes care of it
>>> ''.join(set(word_1).intersection(word_2))
'oe'

set将返回字符串中的唯一字符。set.intersection方法将返回两个集合中通用的字符。


如果for循环对您来说是必须的,那么您可以使用列表理解

>>> unique_1 = [w for w in set(word_1) if w in word_2]
# OR
# >>> unique_2 = [w for w in set(word_2) if w in word_1]
>>> ''.join(unique_1)  # Or, ''.join(unique_2)
'oe'

上述结果也可以通过显式for循环实现,如下所示:

my_str = ''
for w in set(word_1):
if w in word_2:
my_str += w
# where `my_str` will hold `'oe'`

对于这种问题,最好使用 sets:

wrd = 'one'
sec_wrd = 'toe'
wrd = set(wrd)
sec_wrd = set(sec_wrd)
print(''.join(sorted(wrd.intersection(sec_wrd))))

我今天刚刚在代码信号上解决了这个问题。它适用于所有测试。

def solution(s1, s2):
common_char = ""
for i in s1:
if i not in common_char:

i_in_s1 = s1.count(i)
i_in_s2 = s2.count(i)

comm_num = []
comm_num.append(i_in_s1)
comm_num.append(i_in_s2)

comm_i = min(comm_num)
new_char = i * comm_i
common_char += new_char


return len(common_char)

解决问题的函数

def find_common_characters(msg1,msg2):
#to remove duplication set() is used.
set1=set(msg1)
set2=set(msg2)
remove={" "}
#if you wish to exclude space
set3=(set1&set2)-remove
msg=''.join(set3)
return msg

提供输入和调用函数为 msg1,msg2 提供不同的值并测试程序

msg1="python"
msg2="Python"
common_characters=find_common_characters(msg1,msg2)
print(common_characters)

如果你想要它们之间的常用字符数,这是你的一行代码!

def solution(s1,s2):
return sum(min(s1.count(x),s2.count(x)) for x in set(s1))

最新更新