Given a List, extract Kth occurrence of Even Element.
Input : test_list = [4, 6, 2, 3, 8, 9, 10, 11], K = 3
Output : 8
Explanation : K = 3, i.e 0 based index, 4, 6, 2 and 4th is 8.Input : test_list = [4, 6, 2, 3, 8, 9, 10, 11], K = 2
Output : 2
Explanation : K = 2, i.e 0 based index, 4, 6, and 3rd is 2.
Method #1 : Using list comprehension
In this, we extract list of even elements using % operator and use list index access to get Kth even element.
Python3
test_list
=
[
4
,
6
,
2
,
3
,
8
,
9
,
10
,
11
]
print
[
"The original list is : "
+
str
[test_list]]
K
=
4
res
=
[ele
for
ele
in
test_list
if
ele
%
2
=
=
0
][K]
print
[
"The Kth Even Number : "
+
str
[res]]
Output
The original list is : [4, 6, 2, 3, 8, 9, 10, 11] The Kth Even Number : 10
Method #2 : Using filter[] + lambda
In this, task of finding even elements is done using filter[] + lambda function.
Python3
test_list
=
[
4
,
6
,
2
,
3
,
8
,
9
,
10
,
11
]
print
[
"The original list is : "
+
str
[test_list]]
K
=
4
res
=
list
[
filter
[
lambda
ele : ele
%
2
=
=
0
, test_list]][K]
print
[
"The Kth Even Number : "
+
str
[res]]
Output
The original list is : [4, 6, 2, 3, 8, 9, 10, 11] The Kth Even Number : 10
Sometimes, while working with Python, we can have a problem in which we need to perform the pairing of each character with every other in String. This can have application in many domains including web development and day-day. Lets discuss certain ways in which this task can be performed.
Method #1 : Using loop This task can be performed using loop. This a brute force manner in which this task can be performed. In this, we iterate each character and append the Kth letter to each and construct a list.
Python3
test_str
=
"geeksforgeeks"
print
[
"The original string is : "
+
test_str]
K
=
4
res
=
[]
for
ele
in
test_str:
res.append[test_str[K]
+
ele]
print
[
"List after pairing : "
+
str
[res]]
Output :
The original string is : geeksforgeeks List after pairing : ['sg', 'se', 'se', 'sk', 'ss', 'sf', 'so', 'sr', 'sg', 'se', 'se', 'sk', 'ss']
Method #2 : Using join[] + zip[] + cycle[] The combination of above functions can be used to perform this task. In this, we perform the task of joining using join[]. The task of pairing with all is done with zip[] + cycle[].
Python3
from
itertools
import
cycle
test_str
=
"geeksforgeeks"
print
[
"The original string is : "
+
test_str]
K
=
4
res
=
list
[
map
[''.join,
zip
[cycle[test_str[K]], test_str]]]
print
[
"List after pairing : "
+
str
[res]]
Output :
The original string is : geeksforgeeks List after pairing : ['sg', 'se', 'se', 'sk', 'ss', 'sf', 'so', 'sr', 'sg', 'se', 'se', 'sk', 'ss']
The Time and Space Complexity for all the methods are the same:
Time Complexity: O[nlogn]
Auxiliary Space: O[n]