列印兩個字串中按字母順序排列的公共字元的 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

更新於: 23-Jun-2020

905 檢視

啟動你的 職業生涯

完成課程取得認證

立即開始
廣告
© . All rights reserved.