Python 显示这些重复字符的计数
接受两个字符串S1和S2。显示两个字符串中通用的所有字符。也, 显示这些重复字符的计数Python 显示这些重复字符的计数,python,Python,接受两个字符串S1和S2。显示两个字符串中通用的所有字符。也, 显示这些重复字符的计数 # Python3 program MAX_CHAR=26 def printCommon( s1, s2): a1 = [0 for i in range(MAX_CHAR)] a2 = [0 for i in range(MAX_CHAR)] length1 = len(s1) length2 = len(s2) for i in range(0,
# Python3 program
MAX_CHAR=26
def printCommon( s1, s2):
a1 = [0 for i in range(MAX_CHAR)]
a2 = [0 for i in range(MAX_CHAR)]
length1 = len(s1)
length2 = len(s2)
for i in range(0,length1):
a1[ord(s1[i]) - ord('a')] += 1
for i in range(0,length2):
a2[ord(s2[i]) - ord('a')] += 1
for i in range(0,MAX_CHAR):
if (a1[i] != 0 and a2[i] != 0):
for j in range(0,min(a1[i],a2[i])):
ch = chr(ord('a')+i)
print (ch, end=' ')
if __name__=="__main__":
s1=input("Enter first string:")
s2=input("Enter second string:")
print("Common Characters in Alphabetical Orders")
printCommon(s1, s2);
到目前为止,我能够收集两个字符串并显示两个Sting中常见的字符,但无法理解如何显示重复字符的计数
# Python3 program
MAX_CHAR=26
def printCommon( s1, s2):
a1 = [0 for i in range(MAX_CHAR)]
a2 = [0 for i in range(MAX_CHAR)]
length1 = len(s1)
length2 = len(s2)
for i in range(0,length1):
a1[ord(s1[i]) - ord('a')] += 1
for i in range(0,length2):
a2[ord(s2[i]) - ord('a')] += 1
for i in range(0,MAX_CHAR):
if (a1[i] != 0 and a2[i] != 0):
for j in range(0,min(a1[i],a2[i])):
ch = chr(ord('a')+i)
print (ch, end=' ')
if __name__=="__main__":
s1=input("Enter first string:")
s2=input("Enter second string:")
print("Common Characters in Alphabetical Orders")
printCommon(s1, s2);
如何收集和显示重复字符的计数?通过使用Python中的内置集合数据类型,可以找到交叉点(即两者中都存在的字符):
common = set(S1) & set(S2)
然后,您可以使用集合对这些字符的出现次数进行计数。使用两个字符串对计数器进行计数,并对公共字母进行迭代,或者对公共字母进行迭代,并在S1
和S2
中查找每个字符的计数:
import collections
common = set(S1) & set(S2)
c = collections.Counter(S1 + S2)
for char in common:
print(char, c[char])
什么计数:两者中的计数(在A中出现两次,在B中出现3次)计数公共(示例中为2次?)公共字符的总数?你能精确回答你的问题吗?什么是重复字符?提供一些您想要的示例和输出。