Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

List Comprehension 및 OrderedDict를 사용하는 Python의 K' 비반복 문자

<시간/>

이 기사에서는 List Comprehension과 OrderedDict를 사용하여 Python에서 K' Non-repeating Character에 대해 배울 것입니다. 그렇게 하기 위해 우리는 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

결론

이 기사에서는 List Comprehension 및 OrderedDict를 사용하여 Python에서 K' 비반복 문자를 찾았습니다.