![](/img/trans.png)
[英]Write a python program to display all the common characters between two strings
[英]Counting common characters between two strings in python
我有一個我一直在處理的代碼,但它的輸出沒有我需要的那么好。 我必須為 python 中的代碼編寫自己的算法來計算輸入字符串中的字符數。 它就像針頭方法中的大海撈針,但我不應該使用任何文本比較方法,例如 count() 和 findall()。 我希望我的代碼逐個字符地計算並且不計算重疊的字母。 我正在尋找最長的公共子串。 到目前為止,這是我的代碼,但輸出仍然錯誤。 當我在 String1 字段中鍵入“aaaaa”和在 String 2 字段中鍵入“aa”時,它輸出 1,但它應該輸出 2,因為“aaaaa”中有 2 個“aa”沒有重疊。
test1 = input("String1: ")
test2 = input("String2: ")
common = {}
if len(test1)<len(test2):
for letter in test1:
if letter in test2:
common[letter]= 1
else:
for letter in test2:
if letter in test1:
common[letter]= 1
print (len(common))
因此,您的代碼的問題之一是您計算字符出現次數的方式,如果您執行“aaaa”和“aa”,則像您所說的那樣輸出為 2,但在您當前的代碼中,無論如何它將為 1。 這是修復。
import re
test1 = input("String1: ")
test2 = input("String2: ")
common = {}
if len(test1) < len(test2):
for letter in test1:
if letter in test2:
common[letter] = len(re.findall(letter, test2))
else:
for letter in test2:
if letter in test1:
common[letter] = len(re.findall(letter, test1))
for word, count in common.items():
print("{0}\t{1}".format(word,count))
str1=input()
str2=input()
cnt=0
if len(str1)<len(str2):
for i in str1:
if i in str2:
cnt+=1
else:
for i in str2:
if i in str1:
cnt+=1
print(cnt)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.