Given a list of words in Python, the task is to remove the Nth occurrence of the given word in that list.
Examples:
Input: list - ["Lazyroar", "for", "Lazyroar"] word = Lazyroar, N = 2 Output: list - ["Lazyroar", "for"]
Input: list - ["can", "you", "can", "a", "can" "?"] word = can, N = 1 Output: list - ["you", "can", "a", "can" "?"]
Approach #1: By taking another list.
Make a new list, say newList. Iterate the elements in the list and check if the word to be removed matches the element and the occurrence number, otherwise, append the element to newList.
Python3
# Python3 program to remove Nth # occurrence of the given word # Function to remove Ith word def RemoveIthWord(lst, word, N): newList = [] count = 0 # iterate the elements for i in lst: if (i = = word): count = count + 1 if (count ! = N): newList.append(i) else : newList.append(i) lst = newList if count = = 0 : print ( "Item not found" ) else : print ( "Updated list is: " , lst) return newList # Driver code list = [ "Lazyroar" , "for" , "Lazyroar" ] word = "Lazyroar" N = 2 RemoveIthWord( list , word, N) |
Updated list is: ['Lazyroar', 'for']
Approach #2: Remove from the list itself.
Instead of making a new list, delete the matching element from the list itself. Iterate the elements in the list and check if the word to be removed matches the element and the occurrence number, If yes delete that item and return true. If True is returned, print List otherwise, print “Item not Found”.
Python3
# Python3 program to remove Nth # occurrence of the given word # Function to remove Ith word def RemoveIthWord( list , word, N): count = 0 for i in range ( 0 , len ( list )): if ( list [i] = = word): count = count + 1 if (count = = N): del ( list [i]) return True return False # Driver code list = [ 'Lazyroar' , 'for' , 'Lazyroar' ] word = 'Lazyroar' N = 2 flag = RemoveIthWord( list , word, N) if (flag = = True ): print ( "Updated list is: " , list ) else : print ( "Item not Updated" ) |
Updated list is: ['Lazyroar', 'for']
Approach #3: Remove from the list using pop().
Instead of creating a new list and using an if/else statement, we can pop the matching element from the list using pop( ). We need to use an additional counter to keep track of the index.
Why do we need an index? because pop( ) needs index to pass inside i.e pop(index).
Python3
# Python3 program to remove Nth # occurrence of the given word # Function to remove nth word def omit(list1, word, n1): # for counting the occurrence of word count = 0 # for counting the index number # where we are at present index = 0 for i in list1: index + = 1 if i = = word: count + = 1 if count = = n1: # (index-1) because in list # indexing start from 0th position list1.pop(index - 1 ) return list1 # Driver code list1 = [ "he" , "is" , "ankit" , "is" , "raj" , "is" , "ankit raj" ] word = "is" n1 = 3 print ( "new list is :" , omit(list1, word, n1)) |
new list is : ['he', 'is', 'ankit', 'is', 'raj', 'ankit raj']
Time complexity: O(n) where n is the length of the input list.
Auxiliary space: O(1)
because it only uses a fixed amount of extra space to store the count and index variables, and no additional data structures are created.
Approach #4: Using List Comprehension
- Step 1: Initialize a variable count to 0.
- Step 2: Use list comprehension to create a new list with elements of the original list except for the n1th occurrence of word.
a. If the current element is not equal to word, add it to the new list.
b. If the current element is equal to word, increment the count variable. If the count is equal to n1, skip adding this element to the new list. - Step 3: Return the new list.
Python3
def omit(list1, word, n1): count = 0 new_list = [] for i in list1: if i ! = word or (i = = word and count ! = n1): new_list.append(i) if i = = word: count + = 1 return new_list # Driver code list1 = [ "he" , "is" , "ankit" , "is" , "raj" , "is" , "ankit raj" ] word = "is" n1 = 3 print ( "new list is :" , omit(list1, word, n1)) |
new list is : ['he', 'is', 'ankit', 'is', 'raj', 'is', 'ankit raj']
Time Complexity: O(n), where n is the length of the input list.
Auxiliary Space: O(n), as we are creating a new list to store the filtered elements.
Method 5: recursive approach. Here are the steps for the recursive approach:
- Define the function omit(list1, word, n1).
- Check if the list is empty. If it is, return an empty list.
- Check if the first element of the list is the word and if the count of the word is less than n1. If both conditions are true, remove the first element and recursively call the function with the updated list, the same word, and n1 minus 1.
- If the first element of the list is not the word or the count of the word has reached n1, append the first element to a new list and recursively call the function with the rest of the list, the same word, and the same n1.
- Return the new list.
Python3
def omit(list1, word, n1): if not list1: return [] if list1[ 0 ] = = word and n1 > 0 : return omit(list1[ 1 :], word, n1 - 1 ) return [list1[ 0 ]] + omit(list1[ 1 :], word, n1) # Driver code list1 = [ "he" , "is" , "ankit" , "is" , "raj" , "is" , "ankit raj" ] word = "is" n1 = 3 print ( "new list is :" , omit(list1, word, n1)) |
new list is : ['he', 'ankit', 'raj', 'ankit raj']
Time complexity: O(n), where n is the length of the input list, as the function needs to iterate through the entire list once.
Auxiliary space: O(n), as the function creates a new list to store the elements that are not removed.
Approach #6: Using a Generator Function
- Define a generator function that takes the input list, the word to remove, and the number of occurrences of the word to remove.
- Use a loop to iterate through each element of the input list.
- If the current element is not equal to the word to remove, yield it. Otherwise, decrement the counter and yield the element only if the counter is greater than zero.
- Use the generator function to create a new list with the desired elements.
- Return the new list.
Python3
def remove_word(list1, word, n1): def generator(): count = 0 for i in list1: if i ! = word or (i = = word and count ! = n1): yield i if i = = word: count + = 1 return list (generator()) # Driver code list1 = [ "he" , "is" , "ankit" , "is" , "raj" , "is" , "ankit raj" ] word = "is" n1 = 3 print ( "New list is :" , remove_word(list1, word, n1)) |
OUTPUT: New list is : ['he', 'is', 'ankit', 'is', 'raj', 'is', 'ankit raj']
Time Complexity: O(n), where n is the length of the input list.
Auxiliary Space: O(1), since we only need to store a constant number of variables (the loop index, the counter, and the element) at any given time.
Approach #5: Using NumPy
In this approach, we will use the NumPy library to solve the problem. We can convert the given list to a NumPy array and then use NumPy’s delete function to remove the Nth occurrence of the given word.
Algorithm:
- Convert the given list to a NumPy array using the np.array() method.
- Find the indices of the Nth occurrence of the given word using the np.where() method.
- If the number of occurrences is less than N, print “Item not found” and return the original list.
- Otherwise, use the np.delete() method to remove the Nth occurrence of the given word from the NumPy array.
- Convert the modified NumPy array back to a list using the tolist() method and return it.
Python3
import numpy as np def RemoveIthWord( list , word, N): # convert the given list to a NumPy array arr = np.array( list ) # find the indices of the Nth # occurrence of the given word indices = np.where(arr = = word)[ 0 ] # if the number of occurrences is less # than N, print "Item not found" and # return the original list if len (indices) < N: print ( "Item not found" ) return list # use the np.delete() method to remove # the Nth occurrence of the given word # from the NumPy array arr = np.delete(arr, indices[N - 1 ]) # convert the modified NumPy array # back to a list and return it new_list = arr.tolist() print ( "Updated list is:" , new_list) return new_list # Driver Code list = [ "Lazyroar" , "for" , "Lazyroar" ] word = "Lazyroar" N = 2 RemoveIthWord( list , word, N) |
Output:
Updated list is: ['Lazyroar', 'for']
Time Complexity:
The time complexity of this approach depends on the time complexity of the NumPy functions used. In our case, the time complexity of np.array(), np.where(), np.delete(), and tolist() methods are O(1), O(n), O(n), and O(n), respectively. Therefore, the overall time complexity of this approach is O(n).
Space Complexity:
The space complexity of this approach depends on the size of the NumPy array created. In our case, the space complexity is O(n) because we create a NumPy array of size n where n is the length of the input list.