Examples:
Input: str = pythonengineering, k = 3 Output: r First non-repeating character is f, second is o and third is r. Input: str = pythonengineering, k = 2 Output: o Input: str = pythonengineering, k = 4 Output: Less than k non-repeating characters in input.
This problem has an existing solution, please refer to the List Comp Representation and < code class = "comments"> # OrderedDict returns dictionary data Output: This article courtesy of Shashank Mishra (Gullu) . If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting an article contribute @ python.engineering. See my article appearing on the Python.Engineering homepage and help other geeks. Please post comments if you find anything wrong or if you’d like to share more information on the topic discussed above. # Function for finding the kth non-repeating character
# in a line
from
collections
import
OrderedDict
def
kthRepeating (
input
, k):
# structure with input characters
# string as keys in the same order as they are
# were inserted and 0 as default
dict
=
OrderedDict.fromkeys (
input
,
0
)
# now go to the input line to calculate
# frequency of each character
for
ch
in
input
:
dict
[ch]
+
=
1
# now retrieve a list of all keys whose value
# 1 from the order dictionary
nonRepeatDict
=
[key
for
(key, value )
in
code>
dict
. iteritems ()
if
value
=
=
1
]
# now returns the (k-1) th character from the list above
if
len
(nonRepeatDict) & lt; k:
return
’Less than k non
-
repeating
characters
in
input
. ’
else
:
return
nonRepeatDict [k
-
1
]
# Driver function
if
__ name__
=
=
"__ main __"
:
input
=
"pythonengineering"
k
=
3
print
kthRepeating (
input
, k)
r
K-th non-repeating character in Python using list comprehension and OrderedDict Python functions: Questions
K-th non-repeating character in Python using list comprehension and OrderedDict repeat: Questions