Python 列表推導和有序字典中第 K 個不重複字元


在本文中,我們將學習如何利用 Python 列表推導和有序字典獲得第 K 個不重複字元。為此,我們將藉助 Python 中的內建結構。

演算法

1. First, we form a dictionary data from the input.
2. Now we count the frequency of each character.
3. Now we extract the list of all keys whose value equals 1.
4. Finally, we return k-1 character.

示例

from collections import OrderedDict
import itertools
def kthRepeating(inp,k):
   # returns a dictionary data
   dict=OrderedDict.fromkeys(inp,0)
      # frequency of each character
   for ch in inp:
      dict[ch]+=1
   # now extract list of all keys whose value is 1
   nonRepeatDict = [key for (key,value) in dict.items() if value==1]
   # returns (k-1)th character
   if len(nonRepeatDict) < k:
      return 'no ouput.'
   else:
      return nonRepeatDict[k-1]
# Driver function
if __name__ == "__main__":
   inp = "tutorialspoint"
   k = 3
   print (kthRepeating(inp, k))

輸出

a

總結

在本文中,我們利用列表推導和有序字典找到了 Python 中的第 K 個不重複字元。

更新時間: 2019 年 8 月 29 日

269 次檢視

開始你的 職業生涯

完成課程後獲得認證

開始
廣告
© . All rights reserved.