Python | Extract odd length words in String
Last Updated :
01 Jun, 2023
Sometimes, while working with Python, we can have a problem in which we need to extract certain length words from a string. This can be extraction of odd length words from the string. This can have application in many domains including day-day programming. Lets discuss certain ways in which this task can be performed.
Method #1 : Using loop This is brute force way in which this task can be performed. In this, we first split the string to words and then perform iteration to get the odd length words.
Python3
test_str = "gfg is best of geeks"
print ( "The original string is : " + test_str)
res = []
for ele in test_str.split():
if len (ele) % 2 :
res.append(ele)
print ( "The odd length strings are : " + str (res))
|
Output :
The original string is : gfg is best of geeks
The odd length strings are : ['gfg', 'geeks']
Method #2: Using list comprehension This task can also be performed using list comprehension. In this, we perform the task in similar way as above. Just the difference is that its a one-liner.
Python3
test_str = "gfg is best of geeks"
print ( "The original string is : " + test_str)
res = [ele for ele in test_str.split() if len (ele) % 2 ]
print ( "The odd length strings are : " + str (res))
|
Output :
The original string is : gfg is best of geeks
The odd length strings are : ['gfg', 'geeks']
Method 3: Using enumerate function
Python3
n = "geeks for geek"
s = n.split( " " )
print ([x for i,x in enumerate (s) if len (x) % 2 ! = 0 ])
|
The Time and Space Complexity for all the methods are the same:
Time Complexity: O(n)
Auxiliary Space: O(n)
Method 4: Using join() + split() + filter() + list() + lambda functions
Python3
test_str = "gfg is best of geeks"
print ( "The original string is : " + test_str)
res = ' ' .join( list ( filter ( lambda x: len (x) % 2 ! = 0 , test_str.split())))
print ( "The odd length strings are : " + str (res))
|
Output
The original string is : gfg is best of geeks
The odd length strings are : gfg geeks
Time Complexity: O(n)
Auxiliary Space: O(n)
Method : Using Recursion
Python3
def oddLengthWords(itr,list1,word = ''):
if itr = = len (list1):
return word
if len (list1[itr]) % 2 :
word = word + (list1[itr]) + ' '
return oddLengthWords(itr + 1 ,list1,word)
test_str = "gfg is best of geeks"
print ( "The original string is : " + test_str)
l = [i for i in test_str.split()]
res = oddLengthWords( 0 ,l)
print ( "The odd length strings are : " + str (res))
|
Output
The original string is : gfg is best of geeks
The odd length strings are : gfg geeks
Time Complexity: O(n)
Auxiliary Space: O(n)
Method : Using regular expressions
Python3
import re
test_str = "gfg is best of geeks"
print ( "The original string is : " + test_str)
res = [x for x in re.findall(r '\b\w{1,}\b' , test_str) if len (x) % 2 ]
print ( "The odd length strings are : " + str (res))
|
Output
The original string is : gfg is best of geeks
The odd length strings are : ['gfg', 'geeks']
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #5 : Using numpy
Python3
import numpy as np
def extract_odd_length_words(string):
words = np.array(string.split())
lengths = np.vectorize( len )(words)
odd_length_indices = np.where(lengths % 2 ! = 0 )
odd_length_words = words[odd_length_indices]
return odd_length_words
test_str = "gfg is best of geeks"
result = extract_odd_length_words(test_str)
print (result)
|
Output:
[‘gfg’ ‘geeks’]
Time Complexity: O(n)
Auxiliary Space: O(n)
METHOD 6: Using reduce() function
Approach/Intuition:
In this approach, we use the reduce() function to iterate over the words in the input string, and filter out the words with odd length. Finally, we get a list of odd length words.
Algorithm:
- Take the input string from the user.
- Split the string into a list of words using the split() function.
- Define a lambda function to check if the length of the word is odd.
- Use the reduce() function from functools module to combine the filtered words to a single list.
- Print the list of odd length words.
Python3
from functools import reduce
input_str = "gfg is best of geeks"
word_list = input_str.split()
odd_len_words = reduce ( lambda x, y: x + [y] if len (y) % 2 ! = 0 else x, word_list, [])
print ( "The odd length strings are : ['" + "', '" .join(odd_len_words) + "']" )
|
Output
The odd length strings are : ['gfg', 'geeks']
Time Complexity: O(n), where n is the number of words in the input string.
Space Complexity: O(m), where m is the number of odd length words in the input string.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...