使用列表理解和OrderedDict在Python中的第K个非重复字符
在本文中,我们将使用ListComprehension和OrderedDict了解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 = "nhooo"
k = 3
print (kthRepeating(inp, k))输出结果
a
结论
在本文中,我们使用ListComprehension和OrderedDict在Python中找到了第K个非重复字符。
热门推荐
10 教育机构搬迁祝福语简短
11 龙岗儿童蛋糕祝福语简短
12 恭贺新婚搞笑祝福语简短
13 闺女结婚红包祝福语简短
14 升职蛋糕祝福语大全简短
15 有病儿童祝福语简短
16 给亲戚祝福语大全简短
17 丹田老师祝福语简短励志
18 事业祝福语男人的话简短