Open In App

Python – Remove characters greater than K

Improve
Improve
Like Article
Like
Save
Share
Report

Given the Strings list, remove all the characters from each string that have characters greater than K.

Input : test_list = [“geeksforgeeks”, “is”, “best”, “for”, “geeks”], K = 13 
Output : [‘geekfgeek’, ‘i’, ‘be’, ‘f’, ‘geek’] 
Explanation : ASCII Characters above m are removed.

Input : test_list = [“geeksforgeeks”, “is”, “best”, “for”, “geeks”], K = 10 
Output : [‘geekfgeek’, ‘i’, ‘be’, ‘f’, ‘geek’] 
Explanation : ASCII Characters above j are removed. 

Method #1 : Using loop + ord()

In this, we check for the character’s ASCII value using ord(), and then compare it with K, if the character is greater than K, the character is not included in the result string.

Python3




# Python3 code to demonstrate working of
# Remove characters greater than K
# Using loop + ord()
 
# initializing list
test_list = ["geeksforgeeks", "is", "best", "for", "geeks"]
 
# printing original lists
print("The original list is : " + str(test_list))
 
# initializing K
K = 13
 
res = []
for ele in test_list:
    res_str = ''
    for sub in ele:
 
        # check for string characters
        if (ord(sub) - 97 <= K):
            res_str += sub
    res.append(res_str)
 
# printing result
print("Filtered List " + str(res))


Output

The original list is : ['geeksforgeeks', 'is', 'best', 'for', 'geeks']
Filtered List ['geekfgeek', 'i', 'be', 'f', 'geek']

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #2 : Using join() + list comprehension + ord()

This is a shorthand way in which this task can be performed. In this, we perform tasks of filtering and joining to form string using join().

Python3




# Python3 code to demonstrate working of
# Remove characters greater than K
# Using join() + list comprehension + ord()
 
# initializing list
test_list = ["geeksforgeeks", "is", "best", "for", "geeks"]
 
# printing original lists
print("The original list is : " + str(test_list))
 
# initializing K
K = 13
 
# using list comprehension for 1 liner
res = [''.join([ele for ele in sub if ord(ele) - 97 <= K]) for sub in test_list]
 
# printing result
print("Filtered List " + str(res))


Output

The original list is : ['geeksforgeeks', 'is', 'best', 'for', 'geeks']
Filtered List ['geekfgeek', 'i', 'be', 'f', 'geek']

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #3: Without any inbuilt methods

Python3




# Python3 code to demonstrate working of
# Remove characters greater than K
 
# initializing list
test_list = ["geeksforgeeks", "is", "best", "for", "geeks"]
 
# printing original lists
print("The original list is : " + str(test_list))
 
# initializing K
K = 13
alphabets="abcdefghijklmnopqrstuvwxyz"
 
res = []
for ele in test_list:
    res_str = ''
    for sub in ele:
        # check for string characters
        if sub not in alphabets[K:] :
            res_str += sub
    res.append(res_str)
 
# printing result
print("Filtered List " + str(res))


Output

The original list is : ['geeksforgeeks', 'is', 'best', 'for', 'geeks']
Filtered List ['geekfgeek', 'i', 'be', 'f', 'geek']

Time Complexity: O(n) where n is the number of elements in the list “test_list”.  
Auxiliary Space: O(n), where n is the number of elements in the new res list 

Method #4:  Here’s another approach using the filter() function to achieve the same result.

Algorithm for Remove characters greater than K using filter() function approach:

Initialize a list of strings called test_list.
Initialize a variable K with a value of 13.
Initialize a string called alphabets with all the lowercase English alphabets.
Initialize an empty list called res.
For each string in test_list, do the following steps:
a. Use the filter() function to iterate over each character in the string.
b. For each character, use the index() function to get its index in the alphabets string.
c. If the index is less than or equal to K, keep the character, otherwise remove it.
d. Join the remaining characters together to form a new string and append it to the res list.
Print the filtered list.

Python3




# Python3 code to demonstrate working of
# Remove characters greater than K
# Using filter() function
 
# initializing list
test_list = ["geeksforgeeks", "is", "best", "for", "geeks"]
 
# printing original lists
print("The original list is : " + str(test_list))
 
# initializing K
K = 13
alphabets = "abcdefghijklmnopqrstuvwxyz"
 
res = []
for ele in test_list:
    res_str = ''.join(filter(lambda x: alphabets.index(x) <= K, ele))
    res.append(res_str)
 
# printing result
print("Filtered List " + str(res))


Output

The original list is : ['geeksforgeeks', 'is', 'best', 'for', 'geeks']
Filtered List ['geekfgeek', 'i', 'be', 'f', 'geek']

Time complexity: O(n * m), where n is the number of strings in test_list and m is the maximum length of a string in test_list. This is because the filter() function needs to iterate over each character in each string in test_list, which can take up to m iterations for each string.

Auxiliary space complexity: O(n * m), where n is the number of strings in test_list and m is the maximum length of a string in test_list. This is because we need to store the new filtered strings in the res list, which can take up to m characters for each string.

Method#5: Using Recursive method.
Algorithm:
1. Define a function remove_chars that takes a list of strings test_list and an integer K as inputs.
2. If the length of test_list is 0, return an empty list [].
3. Otherwise, take the first string from test_list and iterate through its characters:
  a. If the character’s ASCII value minus 97 is less than or equal to K, add it to a new string res_str.
  b. Otherwise, skip the character.
4. Add the new string res_str to the result list.
5. Recursively call remove_chars with the remaining strings in test_list (i.e., from the second string onwards) and the same value of K.
6. Return the result list.

Python3




def remove_chars(test_list, K):
    if len(test_list) == 0:
        return []
    else:
        res_str = ''
        for sub in test_list[0]:
            if (ord(sub) - 97 <= K):
                res_str += sub
        return [res_str] + remove_chars(test_list[1:], K)
 
test_list = ["geeksforgeeks", "is", "best", "for", "geeks"]
K = 13
print("The original list is : " + str(test_list))
 
res = remove_chars(test_list, K)
print("Filtered List " + str(res))


Output

The original list is : ['geeksforgeeks', 'is', 'best', 'for', 'geeks']
Filtered List ['geekfgeek', 'i', 'be', 'f', 'geek']

Time complexity:
The time complexity of this recursive method is O(nm), where n is the number of strings in the input list and m is the maximum length of any string in the list. This is because we iterate through each character of each string in the list, and the worst-case scenario is when all strings are the same length.

Space complexity:
The space complexity of this recursive method is O(nm), where n is the number of strings in the input list and m is the maximum length of any string in the list. This is because we create a new string res_str for each input string, and the worst-case scenario is when all strings are the same length. Additionally, the recursive calls to remove_chars create new frames on the call stack, which can take up additional memory. However, since the maximum depth of the call stack is limited by the number of strings in the input list, the space complexity is still O(nm).

Method  5 : Using map and lambda functions

STEPS : 

Initialize a list of strings test_list containing multiple strings.
Print the original list of strings.
Initialize an integer K to 13.
Initialize a string alphabets containing all lowercase English alphabets.
Use map() function along with lambda functions to apply a specific process to all the strings in the list test_list. In this case, we are filtering out characters greater than K and joining the remaining characters using join() function.
Convert the resulting map object into a list.
Print the resulting filtered list.

Python3




# Python3 code to demonstrate working of
# Remove characters greater than K
# Using map and lambda functions
 
# initializing list
test_list = ["geeksforgeeks", "is", "best", "for", "geeks"]
 
# printing original lists
print("The original list is : " + str(test_list))
 
# initializing K
K = 13
alphabets = "abcdefghijklmnopqrstuvwxyz"
 
res = list(map(lambda x: ''.join(filter(lambda y: alphabets.index(y) <= K, x)), test_list))
 
# printing result
print("Filtered List " + str(res))


Output

The original list is : ['geeksforgeeks', 'is', 'best', 'for', 'geeks']
Filtered List ['geekfgeek', 'i', 'be', 'f', 'geek']

Time complexity: O(n * m), where n is the number of strings in the list and m is the maximum length of a string.
Auxiliary space: O(n * m), where n is the number of strings in the list and m is the maximum length of a string. 



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