Friday, December 27, 2024
Google search engine
HomeLanguagesPython | Vowel indices in String

Python | Vowel indices in String

Sometimes, while working with Python Strings, we can have a problem in which we need to extract indices of vowels in it. This kind of application is common in day-day programming. Lets discuss certain ways in which this task can be performed. 

Method #1 : Using loop This is one way in which this task can be performed. In this we use brute force to perform this task. In this we iterate for each string element and test for vowel. 

Python3




# Python3 code to demonstrate working of
# Vowel indices in String
# Using loop
 
# initializing string
test_str = "neveropen"
 
# printing original string
print("The original string is : " + test_str)
 
# Vowel indices in String
# Using loop
res = []
for ele in range(len(test_str)):
    if test_str[ele] in "aeiou":
        res.append(ele)
 
# printing result
print("The vowel indices are : " + str(res))


Output : 

The original string is : neveropen
The vowel indices are : [1, 2, 6, 9, 10]

Time Complexity: O(N)

Auxiliary Space: O(N)

  Method #2 : Using enumerate() + list comprehension The combination of above methods can also be used to perform this task. In this, we access the index using enumerate() and list comprehension is used to check for vowels. 

Python3




# Python3 code to demonstrate working of
# Vowel indices in String
# Using list comprehension + enumerate()
 
# initializing string
test_str = "neveropen"
 
# printing original string
print("The original string is : " + test_str)
 
# Vowel indices in String
# Using list comprehension + enumerate()
res = [idx for idx, ele in enumerate(test_str) if ele in "aeiou"]
 
# printing result
print("The vowel indices are : " + str(res))


Output : 

The original string is : neveropen
The vowel indices are : [1, 2, 6, 9, 10]

The Time and Space Complexity for all the methods are the same:

Time Complexity: O(n)

Auxiliary Space: O(n)

Method #3 : Using ord() method

Python3




# Python3 code to demonstrate working of
# Vowel indices in String
# Using loop
 
# initializing string
test_str = "neveropen"
 
# printing original string
print("The original string is : " + test_str)
 
# Vowel indices in String
# Using loop
res = []
vow=[97,101,105,111,117]
for ele in range(len(test_str)):
    if ord(test_str[ele]) in vow:
        res.append(ele)
 
# printing result
print("The vowel indices are : " + str(res))


Output

The original string is : neveropen
The vowel indices are : [1, 2, 6, 9, 10]

Time Complexity: O(N)

Auxiliary Space: O(N)

Method #4 : Using operator.countOf() method

Python3




# Python3 code to demonstrate working of
# Vowel indices in String
import operator as op
vowels = "aeiou"
 
# initializing string
test_str = "neveropen"
 
# printing original string
print("The original string is : " + test_str)
 
# Vowel indices in String
# Using loop
res = []
for ele in range(len(test_str)):
    if op.countOf(vowels, test_str[ele]) > 0:
        res.append(ele)
 
# printing result
print("The vowel indices are : " + str(res))


Output

The original string is : neveropen
The vowel indices are : [1, 2, 6, 9, 10]

Time Complexity: O(n)

Auxiliary Space: O(n)

Method#5: Using Recursive method.

Python3




# Python3 code to demonstrate working of
# Vowel indices in String
# Using recursive method
def vowel_indices(string, idx=0, result=None):
    if result is None:
        result = []
    if idx == len(string):
        return result
    if string[idx] in "aeiou":
        result.append(idx)
    return vowel_indices(string, idx + 1, result)
 
# initializing string
test_str = "neveropen"
 
# printing original string
print("The original string is : " + test_str)
 
res=vowel_indices(test_str)
 
# printing result
print("The vowel indices are : " + str(res))
#this code contributed by tvsk


Output

The original string is : neveropen
The vowel indices are : [1, 2, 6, 9, 10]

Time Complexity: O(n)

Space Complexity: O(n)

Method #6 : Using Regex

Python3




# Python3 code to demonstrate working of
# Vowel indices in String
# Using regex
import re
  
# initializing string
test_str = "neveropen"
  
# printing original string
print("The original string is : " + test_str)
  
# Vowel indices in String
# Using regex
vowel_regex = re.compile("[aeiou]")
res = [i.start() for i in vowel_regex.finditer(test_str)]
  
# printing result
print("The vowel indices are : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy


Output

The original string is : neveropen
The vowel indices are : [1, 2, 6, 9, 10]

Time Complexity: O(n) where n is the length of the string

Auxiliary Space: O(1)

Explanation: In this method, we use the re.compile method to compile a regular expression pattern “[aeiou]” which matches the vowels in the string. The re.finditer method returns an iterator yielding match objects for all non-overlapping matches. The start method of each match object returns the starting position of the match. The result of the code is the list of starting positions of all the matches of vowels in the string.

Method #7 : Using Filter() and lambda():

Python3




# Initialize the string
test_str = "neveropen"
# Specify the vowels
vowels = "aeiou"
# printing original string
print("The original string is : " + test_str)
# Find the indices of vowels using filter() function and lambda function
result = list(filter(lambda x: test_str[x] in vowels, range(len(test_str))))
# Print the result
print("The vowel indices are : " + str(result))
#This code is contributed by Jyothi pinjala


Output

The original string is : neveropen
The vowel indices are : [1, 2, 6, 9, 10]

Time Complexity: O(n)

Auxiliary Space: O(n)

Method #8 : Using numpy:

Algorithm:

  1. Create a string ‘test_str’ and initialize it with some value.
  2. Convert the string ‘test_str’ to a list of characters using the built-in list() function.
  3. Create a numpy array using the converted list of characters.
  4. Create another numpy array using the list of vowels in the order ‘aeiou’.
  5. Use the built-in np.isin() function to create a Boolean array indicating whether each character in the ‘test_str’ array is in the ‘aeiou’ array.
  6. Use the built-in np.where() function to get the indices of the True values in the Boolean array returned in step 5.
  7. Access the first array of the tuple returned in step 6 using index 0 and convert it to a list.
  8. Print the list of vowel indices.

Python3




import numpy as np
 
test_str = "neveropen"
# printing original string
print("The original string is : " + test_str)
  
vowel_indices = np.where(np.isin(np.array(list(test_str)), np.array(list("aeiou")))) # returns a tuple of arrays
vowel_indices = vowel_indices[0].tolist() # get the first array and convert to list
 
 
# printing result
print("The vowel indices are : " + str(vowel_indices))
#This code is  contributed by Rayudu.


Output:
The original string is : neveropen
The vowel indices are : [1, 2, 6, 9, 10]

Time Complexity: O(n), where n is the length of the input string ‘test_str’. The time complexity is dominated by the np.isin() function, which has a time complexity of O(n).
Auxiliary Space: O(n), where n is the length of the input string ‘test_str’. The space complexity is dominated by the two numpy arrays created in steps 3 and 4, each of which has a size of n. The remaining space used by the algorithm is constant.

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