Python program to find the character position of Kth word from a list of strings
Last Updated :
28 Apr, 2023
Given a list of strings. The task is to find the index of the character position for the word, which lies at the Kth index in the list of strings.
Examples:
Input : test_list = [“geekforgeeks”, “is”, “best”, “for”, “geeks”], K = 21
Output : 0
Explanation : 21st index occurs in “geeks” and point to “g” which is 0th element of word.
Input : test_list = [“geekforgeeks”, “is”, “best”, “for”, “geeks”], K = 15
Output : 1
Explanation : 15th index occurs in “best” and point to “e” which is 1st element of word.
Method #1 : Using enumerate() + list comprehension
In this, we use nested enumerate() to check indices for words, and strings in the list, list comprehension is used to encapsulate logic in 1 liner.
Python3
test_list = [ "geekforgeeks" , "is" , "best" , "for" , "geeks" ]
print ( "The original list is : " + str (test_list))
K = 20
res = [ele[ 0 ] for sub in enumerate (test_list) for ele in enumerate (sub[ 1 ])]
res = res[K]
print ( "Index of character at Kth position word : " + str (res))
|
Output
The original list is : ['geekforgeeks', 'is', 'best', 'for', 'geeks']
Index of character at Kth position word : 2
Time Complexity: O(n2)
Auxiliary Space: O(n)
Method #2 : Using next() + zip() + count()
In this, we pair up the number of words with their counts using zip(), and accumulate till we don’t reach Kth Index.
Python3
from itertools import count
test_list = [ "geekforgeeks" , "is" , "best" , "for" , "geeks" ]
print ( "The original list is : " + str (test_list))
K = 20
cnt = count()
res = next (j for sub in test_list for j, idx in zip (
range ( len (sub)), cnt) if idx = = K)
print ( "Index of character at Kth position word : " + str (res))
|
Output
The original list is : ['geekforgeeks', 'is', 'best', 'for', 'geeks']
Index of character at Kth position word : 2
Time Complexity: O(n2)
Auxiliary Space: O(n)
Method 3: Using nested loop
Python3
test_list = [ "geekforgeeks" , "is" , "best" , "for" , "geeks" ]
print ( "The original list is : " + str (test_list))
K = 20
idx = 0
for word in test_list:
if idx + len (word) > K:
print ( "Index of character at Kth position word : " + str (K - idx))
break
else :
idx + = len (word)
else :
print ( "K is beyond the end of the list" )
|
Output
The original list is : ['geekforgeeks', 'is', 'best', 'for', 'geeks']
Index of character at Kth position word : 2
Please Login to comment...