Python代码按字母顺序打印两个字符串的公共字符
给出了两个用户输入字符串,我们的任务是按字母顺序打印所有常见字符。
示例
Input: string1: python string2: program Output: op
说明
两个字符串之间的共同字母是o(1次),p(1次)
算法
Step 1: first we take two input string. Step 2: next we will do to convert these two strings into counter dictionary. Step 3: Now find common elements between two strings using intersection ( ) property. Step 4: Resultant will also be a counter dictionary having common elements as keys and their common frequencies as value. Step 5: Use elements () method of the counter dictionary to expand the list of keys by their frequency number of times. Step 6: sort list in ascending order to print a resultant string in alphabetical order. Step 7: join characters without space to produce resultant string.
范例程式码
from collections import Counter
def common(str1,str2):
d1 = Counter(str1)
d2 = Counter(str2)
cdict = d1 & d2
if len(cdict) == 0:
print -1
return
cchars = list(cdict.elements())
cchars = sorted(cchars)
print ("Common characters are ::>",''.join(cchars) )
# Driver program
if __name__ == "__main__":
s1 = input("Enter first string")
s2 = input("Enter second string")
common(s1, s2)输出结果
Enter first string python Enter second string program Common characters are ::> op
热门推荐
10 新年门口花束祝福语简短
11 盘锦结婚祝福语大全简短
12 父母生日祝福语 简短独特
13 家庭恩爱祝福语简短英文
14 高考俄语祝福语大全简短
15 虎年祝福语 诗句唯美简短
16 生日婚礼祝福语简短精辟
17 虎年喝酒拜年祝福语简短
18 教师闺蜜祝福语简短