Sometimes, while programming, we can have a problem in which we need to check for ith and jth character of each string. We may require to extract count of all strings with similar ith and jth characters. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using loop This is brute force method by which this task can be performed. In this, iterate each element of list and check for each string’s ith and jth character and increase the counter in case we find a match.
Python3
test_list = [ 'geeks' , 'beke' , 'treat' , 'neke' ]
print ("The original list : " + str (test_list))
i = 1
j = 3
count = 0
for ele in test_list:
if ele[i] = = ele[j]:
count = count + 1
print ("Total Strings with similar ith and jth elements : " + str (count))
|
Output : The original list : ['geeks', 'beke', 'treat', 'neke']
Total Strings with similar ith and jth elements : 2
Time Complexity: O(n), where n is the length of the input list. This is because we’re using the loop which has a time complexity of O(n) in the worst case.
Auxiliary Space: O(n), as we’re using additional space res other than the input list itself with the same size of input list.
Method #2 : Using sum() + generator expression This is one liner alternative to perform this task. In this, we perform the task of iteration using generator expression and summation using sum().
Python3
test_list = [ 'geeks' , 'beke' , 'treat' , 'neke' ]
print ("The original list : " + str (test_list))
i = 1
j = 3
res = sum ( 1 for ele in test_list if ele[i] = = ele[j])
print ("Total Strings with similar ith and jth elements : " + str (res))
|
Output : The original list : ['geeks', 'beke', 'treat', 'neke']
Total Strings with similar ith and jth elements : 2
Time Complexity: O(n) where n is the number of elements in the string list. The sum() + generator expression is used to perform the task and it takes O(n) time.
Auxiliary Space: O(1) additional constant space is required
Method #3 : Another approach can be using filter() function and lambda function.
Python3
test_list = [ 'geeks' , 'beke' , 'treat' , 'neke' ]
print ( "The original list : " + str (test_list))
i = 1
j = 3
result = len ( list ( filter ( lambda x: x[i] = = x[j], test_list)))
print ( "Total Strings with similar ith and jth elements : " + str (result))
|
OutputThe original list : ['geeks', 'beke', 'treat', 'neke']
Total Strings with similar ith and jth elements : 2
In this approach, we are using the filter() function along with a lambda function to filter out elements from the list test_list that match the condition of having the same value at index i and index j. We then use the len() function to count the number of elements in the filtered list, which gives us the total count of strings with similar ith and jth elements. The time complexity of this approach is O(n) as we are iterating through the list once and the space complexity is O(n) as we are creating a new filtered list.