Open In App

Python program to print even length words in a string

Last Updated : 25 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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="geeks 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="geeks 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="geeks 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 = "geeks 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="geeks 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="geeks 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 = "geeks 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.



Similar Reads

Check if the given string of words can be formed from words present in the dictionary
Given a string array of M words and a dictionary of N words. The task is to check if the given string of words can be formed from words present in the dictionary. Examples: dict[] = { find, a, geeks, all, for, on, geeks, answers, inter } Input: str[] = { "find", "all", "answers", "on", "geeks", "for", "geeks" }; Output: YES all words of str[] are p
15+ min read
Count words that appear exactly two times in an array of words
Given an array of n words. Some words are repeated twice, we need to count such words. Examples: Input : s[] = {"hate", "love", "peace", "love", "peace", "hate", "love", "peace", "love", "peace"}; Output : 1 There is only one word "hate" that appears twice Input : s[] = {"Om", "Om", "Shankar", "Tripathi", "Tom", "Jerry", "Jerry"}; Output : 2 There
6 min read
DFA in LEX code which accepts even number of zeros and even number of ones
Lex is a computer program that generates lexical analyzers, which is commonly used with the YACC parser generator. Lex, originally written by Mike Lesk and Eric Schmidt and described in 1975, is the standard lexical analyzer generator on many Unix systems, and an equivalent tool is specified as part of the POSIX standard. Lex reads an input stream
6 min read
Find the player to last modify a string such that even number of consonants and no vowels are left in the string
Given a string S of length N containing lowercase alphabets. Two players A and B play a game optimally in turns, starting with player A. In each move, either of the following operations can be performed: Remove a consonant from the string.If any character is a vowel, then convert it into any other alphabet. A player loses the game if there is an ev
7 min read
Check if a two character string can be made using given words
Given a string of two characters and n distinct words of two characters. The task is to find if it is possible to arrange given words in such a way that the concatenated string has the given two character string as a substring. We can append a word multiple times. Examples: Input : str = "ya" words[] = {"ah", "oy", "to", "ha"} Output : YES We can j
6 min read
Lex Program to count number of words
Lex is a computer program that generates lexical analyzers and was written by Mike Lesk and Eric Schmidt. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language. Prerequisite: Flex (Fast lexical Analyzer Generator) Example: Input: Hello everyone Output: 2 Input: This is
1 min read
Length of longest substring to be deleted to make a string equal to another string
Given two strings str1 and str2, where str2 is a subsequence of str1, the task is to find the length of the longest substring of str1 which when removed, makes the strings str2 and str1 equal. Examples: Input: str1 = “programmingbloods”, str2 = “ibloods” Output: 8 Explanation: Substrings to be removed from str1 are [“program”, “ng”]. Therefore, the
9 min read
LEX program to print the longest string and to find average of given numbers
Lex :The Lex program has purpose of generating lexical analyzer. Lex analyzers are a program that transform input streams into sequence of tokens. A C program implements the lexical analyzer to read input stream and produce output as the source code. Commands to be used - lex file_name.l // To produce a c program cc lex.yy.c -lfl // To compile the
2 min read
Find length of a string in python (6 ways)
Strings in Python are immutable sequences of Unicode code points. Given a string, we need to find its length. Examples: Input : 'abc' Output : 3 Input : 'hello world !' Output : 13 Input : ' h e l l o ' Output :14 Methods#1: Using the built-in function len. The built-in function len returns the number of items in a container. C/C++ Code # Python co
3 min read
Print all subsequences of a string in Python
Given a string, we have to find out all subsequences of it. A String is a subsequence of a given String, that is generated by deleting some character of a given string without changing its order.Examples: Input : abc Output : a, b, c, ab, bc, ac, abc Input : aaa Output : a, aa, aaa Using Pick and Don’t Pick concept : C/C++ Code def printSubSequence
2 min read
Article Tags :
Practice Tags :