📌  相关文章
📜  根据Python输入字符串中出现的字符生成两个输出字符串

📅  最后修改于: 2022-05-13 01:55:47.930000             🧑  作者: Mango

根据Python输入字符串中出现的字符生成两个输出字符串

给定一个输入字符串str[],生成两个输出字符串。其中一个由在输入字符串中仅出现一次的字符组成,第二个由多次出现的字符组成。必须对输出字符串进行排序。

例子:

Input : str = "geeksforgeeks"
Output : String with characters occurring once:
"for".
String with characters occurring multiple times:
"egks"

Input : str = "geekspractice"
Output : String with characters occurring once:
"agikprst"
String with characters occurring multiple times:
"ce"

我们有解决此问题的现有解决方案,请参阅根据输入字符串链接中出现的字符生成两个输出字符串。我们可以在Python中使用 Counter(iterable) 方法快速解决这个问题。做法很简单,

  1. 使用counter()方法将字符串转换为以字符为键、频率为值的字典。
  2. 现在分离出频率为 1 且频率大于 1 的字符列表。
  3. 对两个列表中的字符进行排序以获得输出字符串。
# Function Generate two output strings depending upon 
# occurrence of character in input string
  
from collections import Counter
  
def generateStrings(input):
      
     # convert string into dictionary
     # having characters as keys and frequency as value
     freqDict = Counter(input)
  
     # separate out characters having frequency 1 and more than 1
     freq1 = [ key for (key,count) in freqDict.items() if count==1]
     freqMore1 = [ key for (key,count) in freqDict.items() if count>1]
  
     # sort lists and concatenate characters
     # with out space to print resultant strings
     freq1.sort()
     freqMore1.sort()
  
     # print output strings
     print ('String with characters occurring once:')
     print (''.join(freq1))
     print ('String with characters occurring multiple times:')
     print (''.join(freqMore1))
  
# Driver program
if __name__ == "__main__":
    input = "geeksforgeeks"
    generateStrings(input)

输出:

String with characters occurring once:
for
String with characters occurring multiple times:
egks