Open In App

Python | Extract odd length words in String

Improve
Improve
Like Article
Like
Save
Share
Report

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




# Python3 code to demonstrate working of
# Extract odd length words in String
# Using loop
 
# initializing string
test_str = "gfg is best of geeks"
 
# printing original string
print("The original string is : " + test_str)
 
# Extract odd length words in String
# Using loop
res = []
for ele in test_str.split():
    if len(ele) % 2 :
        res.append(ele)
 
# printing result
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




# Python3 code to demonstrate working of
# Extract odd length words in String
# Using list comprehension
 
# initializing string
test_str = "gfg is best of geeks"
 
# printing original string
print("The original string is : " + test_str)
 
# Extract odd length words in String
# Using list comprehension
res = [ele for ele in test_str.split() if len(ele) % 2]
 
# printing result
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




# python code to print odd length words
  
n="geeks for geek"
s=n.split(" ")
print([x for i,x in enumerate(s) if len(x)%2!=0])


Output

['geeks', 'for']

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




# Python3 code to demonstrate working of
# Extract odd length words in String
# Using join() + split() + filter() + list() + lambda functions
 
# initializing string
test_str = "gfg is best of geeks"
 
# printing original string
print("The original string is : " + test_str)
 
# Extract odd length words in String
 
res = ' '.join(list(filter(lambda x: len(x) % 2 != 0, test_str.split())))
 
# printing result
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




# Python3 code to demonstrate working of
# Extract odd length words in String
#recursive function to print odd length words
def oddLengthWords(itr,list1,word=''):
    if itr == len(list1): #base condition
        return word
    if len(list1[itr])%2:
        word=word+(list1[itr])+' '
    return oddLengthWords(itr+1,list1,word)
 
test_str = "gfg is best of geeks"
# printing original string
print("The original string is : " + test_str)
 
l=[i for i in test_str.split()]
res=oddLengthWords(0,l)
 
# printing result
print("The odd length strings are : " + str(res))
#this code contributed by tvsk


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
 
# initializing string
test_str = "gfg is best of geeks"
 
# printing original string
print("The original string is : " + test_str)
 
# Extract odd length words in String using regular expressions
res = [x for x in re.findall(r'\b\w{1,}\b', test_str) if len(x)%2]
 
# printing result
print("The odd length strings are : " + str(res))
 
#This code is contributed by Vinay Pinjala.


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
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.



Last Updated : 01 Jun, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads