Sunday, November 17, 2024
Google search engine
HomeLanguagesPython program to print even length words in a string

Python program to print even length words in a string

Given a string. The task is to print all words with even length in the given string.

Examples: 

Input: s = "This is a python language"
Output: This is python language

Input: s = "i am laxmi"
Output: am

Method: Finding even length words using for loop and if statement and without using the def function. First split the given string using the split() function and then iterate the words of a string using for loop. Calculate the length of each word using the len() function. If the length is even, then print the word.

Python3




# Python code
# To print even length words in string
 
#input string
n="This is a python language"
#splitting the words in a given string
s=n.split(" ")
for i in s:
  #checking the length of words
  if len(i)%2==0:
    print(i)
 
# this code is contributed by gangarajula laxmi


Output

This
is
python
language

Time Complexity: O(n), where n is the length of the given string
Auxiliary Space: O(n)

Approach: Split the string using split() function. Iterate in the words of a string using for loop. Calculate the length of the word using len() function. If the length is even, then print the word. Below is the Python implementation of the above approach: 

Python3




# Python3 program to print
# even length words in a string
 
def printWords(s):
     
    # split the string
    s = s.split(' ')
     
    # iterate in words of string
    for word in s:
         
        # if length is even
        if len(word)%2==0:
            print(word)
 
 
# Driver Code
s = "i am muskan"
printWords(s)


Output

am
muskan

Time Complexity: O(n), where n is the length of the given string
Auxiliary Space: O(n)

Method: Using the lambda function

Python3




# Python code
# To print even length words in string
 
#input string
n="Lazyroar for geek"
#splitting the words in a given string
s=n.split(" ")
l=list(filter(lambda x: (len(x)%2==0),s))
print(l)


Output

['geek']

Time Complexity: O(n), where n is the length of the given string
Auxiliary Space: O(n)

Method: Using list comprehension

Python3




# python code to print even length words
 
n="Lazyroar for geek"
s=n.split(" ")
print([x for x in s if len(x)%2==0])


Output

['geek']

Time Complexity: O(n), where n is the length of the given string
Auxiliary Space: O(n)

Method: Using the enumerate function 

Python3




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


Output

['geek']

Time Complexity: O(n), where n is the length of the given string
Auxiliary Space: O(n)

Method : Using Recursion

Python3




#recursive function to print even length words
def PrintEvenLengthWord(itr,list1):
  if itr == len(list1):
    return
  if len(list1[itr])%2 == 0:
    print(list1[itr])
  PrintEvenLengthWord(itr+1,list1)
  return
str = "Lazyroar for geek"
l=[i for i in str.split()]
PrintEvenLengthWord(0,l)


Output

geek

Time Complexity: O(n), where n is the length of the given string
Auxiliary Space: O(n)

Method :  Using the filter function and lambda function:

 Use the filter function and lambda function to find even length words
 

Python




s="Lazyroar for geek"
 
# Split the string into a list of words
words = s.split(" ")
 
# Use the filter function and lambda function to find even length words
even_length_words = list(filter(lambda x: len(x) % 2 == 0, words))
 
# Print the list of even length words
print(even_length_words)
#This code is contributed by Edula Vinay Kumar Reddy


Output

['geek']

The time complexity is O(n), where n is the number of words in the input string.

The Auxiliary space is also O(n), where n is the number of words in the input string.

Method :  Using the itertools.filterfalse() function

Python3




import itertools
s="Lazyroar for geek"
 
# Split the string into a list of words
words = s.split(" ")
 
# Use the itertools.filterfalse function and lambda function to find even length words
even_length_words = list(itertools.filterfalse(lambda x: len(x) % 2 != 0, words))
 
# Print the list of even length words
print(even_length_words)


Output

['geek']

The time complexity is O(n), where n is the total number of characters in the input string ‘s’.

The auxiliary space is O(m), where m is the number of words in the list.

Method: Using replace () function 

Python3




# code
def print_even_length_words(s):
    words = s.replace(',', ' ').replace('.', ' ').split()
    for word in words:
        if len(word) % 2 == 0:
            print(word, end=' ')
 
 
s = "Lazyroar for geek"
print_even_length_words(s)


Output

geek 

This approach has a time complexity of O(n), where n is the length of the string, and an auxiliary space of O(n).

Method: iterative character-by-character parsing

Here are the steps involved in the “iterative character-by-character parsing” approach to solve the problem of printing all words with even length in a given string:

  1. Initialize an empty string variable to store the current word being parsed.
  2. Iterate over each character in the input string:
    a. If the character is a space, it means the current word has ended. So, check if the length of the current word is even and greater than 0. If yes, print the current word.
    b. If the character is not a space, it means the current word is being formed. So, append the character to the current word variable.
  3. After the loop has ended, check if the length of the last word is even and greater than 0. If yes, print the last word.

Python3




# Initialize the input string
s = "This is a python language"
 
# Initialize an empty string variable to store the current word being parsed
word = ''
 
# Iterate over each character in the input string
for i in s:
    # If the character is a space, it means the current word has ended
    if i == ' ':
        # Check if the length of the current word is even and greater than 0
        if len(word)%2 == 0 and len(word)!=0:
            # If yes, print the current word
            print(word,end=' ')
        # Reset the current word variable for the next word
        word = ''
    # If the character is not a space, it means the current word is being formed
    else:
        # Append the character to the current word variable
        word += i
 
# After the loop has ended, check if the length of the last word is even and greater than 0
if len(word)%2 == 0 and len(word)!=0:
    # If yes, print the last word
    print(word,end=' ')


Output

This is python language 

The time complexity of this “iterative character-by-character parsing” approach to print all words with even length in a given string is O(n), where n is the length of the input string.

The auxiliary space complexity of this approach is O(m), where m is the length of the longest word in the input string. 

Method: Using itertools.compress() function

The algorithm for this program is as follows:

  1. Define a string variable n containing a sentence with words of varying lengths.
  2. Split the sentence into a list of words using the split() method and store it in a variable s.
  3. Create a list comprehension to create a boolean list of the same length as the s list, where True is set if the length of the corresponding word in s is even, else False.
  4. Use the compress() function from itertools module to filter the words in s by using the boolean list obtained in step 3.
  5. Store the filtered words in a list called even_len_words.
  6. Print the list of even length words.

Python3




from itertools import compress
 
n = "This is a python language"
s = n.split(" ")
even_len_bool = [len(word)%2==0 for word in s]
even_len_words = list(compress(s, even_len_bool))
print(even_len_words)


Output

['This', 'is', 'python', 'language']

The time complexity of this program is O(n), where n is the length of the sentence. This is because the program splits the sentence into a list of words in O(n) time, and then creates a boolean list of length n in O(n) time. The compress() function operates in O(n) time to filter the list of words, and the final list is printed in O(n) time. Thus, the overall time complexity of this program is O(n). 

The auxiliary space of this program is also O(n) because the list of words and boolean list are created and stored in memory. However, the compressed list may be smaller than the original list in certain cases, resulting in a lower space complexity than O(n).

Approach: Word-by-word parsing

  1. Initialize the variables word_start to 0 and even_words to an empty list.
  2. Loop through each character of the string s using a for loop.
  3. If the current character is a space, set the word_end variable to the index of the space character and calculate the length of the current word by subtracting word_start from word_end. If the length of the word is even, append it to the list of even words.
  4. Set the value of word_start to the index of the next character (i.e., the character immediately after the space).
  5. After the loop, calculate the length of the last word using word_start and the length of the string. If the length of the last word is even, append it to the list of even words.
  6. Loop through the list of even words and print each one.

Python3




s = "I am omkhar"
 
word_start = 0
even_words = []
 
for i in range(len(s)):
    if s[i] == " ":
        word_end = i
        word_length = word_end - word_start
        if word_length % 2 == 0:
            even_words.append(s[word_start:word_end])
        word_start = i + 1
 
word_length = len(s) - word_start
if word_length % 2 == 0:
    even_words.append(s[word_start:])
 
for w in even_words:
    print(w)


Output

am
omkhar

Time complexity: O(n), where n is the length of the input string s.

Auxiliary space: O(m), where m is the number of even-length words in the input string s.

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments