[英]comparing two strings in python with duplicates
我試圖比較兩個字符串:'apple'和'pear'並返回不屬於另一個字符串的字母。
例如,'apple'在'pear'中不包含'r'
'pear'在蘋果中不包含'l'和'p'(梨包含p但不包含兩個p)。
所以我想要一個返回'r','l'和'p'的函數。
我嘗試了set,但它忽略了重復項(在本例中為p)。
def solution(A, B):
N = len(A)
M = len(B)
letters_not_in_B = list(set([c for c in A if c not in B]))
letters_not_in_A = list(set([c for c in B if c not in A]))
answer = len(letters_not_in_B) + len(letters_not_in_A)
return answer
您可以比較參數a
和b
的串聯產生的每個單獨字符串的字符數:
def get_results(a, b):
return list(set([i for i in a+b if a.count(i) != b.count(i)]))
print(get_results('apple', 'pear'))
輸出:
['p', 'r', 'l']
使用Counter
from collections import Counter
Counter('apple') - Counter('pear') # --> Counter({'p': 1, 'l': 1})
Counter('pear') - Counter('apple') # --> Counter({'r': 1})
def solution(a, b):
# create mutable list copies of a and b
list_a = list(a)
list_b = list(b)
for ch in a:
if ch in list_b:
list_b.remove(ch)
for ch in b:
if ch in list_a:
list_a.remove(ch)
return list_a + list_b
最簡單的方法是進行for循環,但如果你想更好地概述數據,你可以在每個字符串上循環,並添加字母和字符串中出現的次數,只需比較這兩個字典和輸出差異。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.