Computer >> Máy Tính >  >> Lập trình >> Python

K’th Ký tự không lặp lại trong Python bằng cách sử dụng tính năng hiểu danh sách và có thứ tự

Trong bài viết này, chúng ta sẽ tìm hiểu về K’th K’th Non-repeat Character trong Python bằng cách sử dụng List Complusive và OrderDict. Để làm như vậy, chúng tôi sử dụng sự trợ giúp của các cấu trúc dựng sẵn có sẵn trong Python.

Thuật toán

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.

Ví dụ

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))

Đầu ra

a

Kết luận

Trong bài viết này, chúng tôi đã tìm thấy Ký tự không lặp lại K’th trong Python bằng cách sử dụng tính năng hiểu danh sách và có thứ tự.