Saturday, December 28, 2024
Google search engine
HomeLanguagesPython – Filter Similar Case Strings

Python – Filter Similar Case Strings

Given the Strings list, the task is to write a Python program to filter all the strings which have a similar case, either upper or lower.

Examples:

Input : test_list = [“GFG”, “Geeks”, “best”, “FOr”, “all”, “GEEKS”] 
Output : [‘GFG’, ‘best’, ‘all’, ‘GEEKS’] 
Explanation : GFG is all uppercase, best is all lowercase.

Input : test_list = [“GFG”, “Geeks”, “best”] 
Output : [‘GFG’, ‘best’] 
Explanation : GFG is all uppercase, best is all lowercase.
 

Method #1 : Using islower() + isupper() + list comprehension

In this, we check for each string to be lower or upper case using islower() and isupper(), and list comprehension is used to iterate through strings.

Python3




# Python3 code to demonstrate working of
# Filter Similar Case Strings
# Using islower() + isupper() + list comprehension
 
# Initializing Matrix
test_list = ["GFG", "Geeks",
             "best", "FOr", "all", "GEEKS"]
 
# Printing original list
print("The original list is : " + str(test_list))
 
# Checking for cases via
# islower() and isupper()
res = [sub for sub in test_list if sub.islower() or sub.isupper()]
 
# Printing result
print("Strings with same case : " + str(res))


Output

The original list is : ['GFG', 'Geeks', 'best', 'FOr', 'all', 'GEEKS']
Strings with same case : ['GFG', 'best', 'all', 'GEEKS']

Method #2: Using islower() + isupper() + filter() + lambda

In this, we perform the task of filtering strings using filter() and lambda function. Rest all the functionality is similar to the above method.

Python3




# Python3 code to demonstrate working of
# Filter Similar Case Strings
# Using islower() + isupper() + filter() + lambda
 
# initializing Matrix
test_list = ["GFG", "Geeks", "best",
             "FOr", "all", "GEEKS"]
              
# printing original list
print("The original list is : " + str(test_list))
 
# islower() and isupper() used to check for cases
# filter() and lambda function used for filtering
res = list(filter(lambda sub : sub.islower() or sub.isupper(), test_list))
 
# printing result
print("Strings with same case : " + str(res))


Output

The original list is : ['GFG', 'Geeks', 'best', 'FOr', 'all', 'GEEKS']
Strings with same case : ['GFG', 'best', 'all', 'GEEKS']

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

Method 3: Using regex (Regular Expression)

Approach: Filter Similar Case Strings Using regex (Regular Expression) 

  1. Import the ‘re’ library.
  2. Create a list of strings named ‘test_list’ and print the original list ‘test_list’.
  3. Use a list comprehension to iterate through ‘test_list’ and filter out the strings which have all uppercase or all lowercase letters.
  4. Use re.match function to match the pattern of uppercase or lowercase in each string.
  5. The pattern ‘[A-Z]+’ matches one or more uppercase letters and the pattern ‘[a-z]+’ matches one or more lowercase letters.
  6. The ‘^’ sign indicates the start of the string, and the ‘$’ sign indicates the end of the string.
  7. Append the matched strings to the list ‘res’.
  8. Print the final filtered list ‘res’.

Python3




import re
 
test_list = ["GFG", "Geeks", "best", "FOr", "all", "GEEKS"]
print("The original list is : " + str(test_list))
 
# Using re.match to match the pattern of uppercase or lowercase
# The pattern '[A-Z]+' matches one or more uppercase letters
# The pattern '[a-z]+' matches one or more lowercase letters
res = [i for i in test_list if re.match(
    '^[A-Z]+$', i) or re.match('^[a-z]+$', i)]
 
print("Strings with same case : " + str(res))


Output

The original list is : ['GFG', 'Geeks', 'best', 'FOr', 'all', 'GEEKS']
Strings with same case : ['GFG', 'best', 'all', 'GEEKS']

Time complexity: O(NM)
The time complexity of the algorithm is O(n*m), where n is the number of strings in the list and m is the average length of each string. The regular expression pattern matching is a linear-time operation, but we need to perform it for each string in the list, so the overall time complexity is proportional to the number of strings and their length.

Auxiliary space complexity: O(K)
The auxiliary space complexity of the algorithm is O(k), where k is the number of strings that match the regular expression pattern. We create a new list ‘res’ to store the filtered strings. The maximum size of this list is k, so the space complexity is proportional to the number of matched strings. The original list ‘test_list’ is not modified, so its space complexity is not considered.

Method #4: Using Numpy

Algorithm:

  1. Create a list of strings called test_list.
  2. Convert the list into a NumPy array called arr.
  3. Use NumPy’s np.char.islower() and np.char.isupper() functions to create two boolean arrays of the same shape as arr. The first array indicates for whether each element of arr is lowercase, and the second array indicates whether each element is uppercase.
  4. Use logical OR to combine the two boolean arrays element-wise, creating a third boolean array that is also of the same shape as arr.
  5. Use the resulting boolean array to index arr, selecting only the elements that have either all lowercase or all uppercase letters.
  6. Print the selected elements as a string along with a message indicating that these are the strings with the same case.

Python3




import numpy as np
 
# Creating list of strings
test_list = ["GFG", "Geeks", "best", "FOr", "all", "GEEKS"]
 
# Printing original list
print("The original list is : " + str(test_list))
 
# Convert the list into a NumPy array
arr = np.array(test_list)
 
# use NumPy's np.char.islower() and np.char.isupper() functions to create a boolean array of the same shape as arr
# that indicates whether each element of arr is lowercase or uppercase
lowercase_arr = np.char.islower(arr)
uppercase_arr = np.char.isupper(arr)
 
# use logical OR to combine the two boolean arrays element-wise
same_case_arr = lowercase_arr | uppercase_arr
 
# use the resulting boolean array to index arr, selecting only the elements that have either all lowercase or all uppercase letters
res = arr[same_case_arr]
 
# print the selected elements as a string along with a message indicating that these are the strings with the same case
print("Strings with same case : " + str(res))
# This code is contributed by Jyothi pinjala


Output

The original list is : ['GFG', 'Geeks', 'best', 'FOr', 'all', 'GEEKS']
Strings with same case : ['GFG', 'best', 'all', 'GEEKS']

Time Complexity: O(NM)

Creating the NumPy array using np.array() takes O(n) time, where n is the number of strings in test_list.
The np.char.islower() and np.char.isupper() functions take O(n * m) time, where m is the average length of a string in arr.
The logical OR operation using the | operator takes O(n * m) time.
Indexing the NumPy array using boolean indexing takes O(k), where k is the number of elements that have either all lowercase or all uppercase letters.
Converting the selected elements to a string using str() takes O(k * m) time.
Overall, the time complexity of the code is O(n * m).

Auxiliary Space: O(NM)

Creating the NumPy array using np.array() takes O(n * m) space.
Creating the two boolean arrays using np.char.islower() and np.char.isupper() takes O(n * m) space.
Creating the third boolean array using logical OR takes O(n * m) space.
Creating the res array using boolean indexing takes O(k * m) space.
Storing the message string takes O(1) space.
Overall, the space complexity of the code is O(n * m).

Method #5: Without any builtin methods

Steps:

  1. Initiated a for loop to traverse the list of strings
  2. Defined two methods check_lower(),check_upper() methods which will check whether the string is uppercase or lowercase by checking whether each character of the string belongs to loweralphabets or upperalphabets
  3. If the function check_lower() or check_upper() returns True then all the characters of the string belong to the same case.
  4. Append such strings to the output list.
  5. Display output list.

Python3




# Python3 code to demonstrate working of
# Filter Similar Case Strings
 
def check_lower(s):
    c = 0
    for i in s:
        if i in "abcdefghijklmnoprstuvwxyz":
            c += 1
    if(c == len(s)):
        return True
    return False
 
def check_upper(s):
    c = 0
    for i in s:
        if i in "ABCDEFGHIJKLMNOPRSTUVWXYZ":
            c += 1
    if(c == len(s)):
        return True
    return False
 
 
# Initializing Matrix
test_list = ["GFG", "Geeks",
             "best", "FOr", "all", "GEEKS"]
 
 
# Printing original list
print("The original list is : " + str(test_list))
 
res = []
for i in test_list:
    if check_upper(i) or check_lower(i):
        res.append(i)
         
# Printing result
print("Strings with same case : " + str(res))


Output

The original list is : ['GFG', 'Geeks', 'best', 'FOr', 'all', 'GEEKS']
Strings with same case : ['GFG', 'best', 'all', 'GEEKS']

Time Complexity: O(N), where N – length of strings list
Auxiliary Space : O(N)

Method 6: Using map() and lambda function

Steps: 

  1. Create a lambda function that takes in a string as an argument and returns True if the string contains all lowercase or all uppercase characters, otherwise False.
  2. Use the ‘map()’ function to apply the lambda function to each element in the ‘test_list’.
  3. Use the ‘filter()’ function to filter out the elements in the resulting map object that are False.
  4. Convert the resulting filter object to a list.
  5. Print the resulting list as the result.

Python3




# Python3 code to demonstrate working of
# Filter Similar Case Strings
 
# lambda function to check if string contains all lowercase
# or all uppercase characters
def check_case(s): return s.islower() or s.isupper()
 
 
# initializing Matrix
test_list = ["GFG", "Geeks", "best", "FOr", "all", "GEEKS"]
 
# printing original list
print("The original list is : " + str(test_list))
 
# using map(), filter(), and lambda function to filter out similar case strings
res = list(filter(check_case, map(str, test_list)))
 
# printing result
print("Strings with same case : " + str(res))


Output

The original list is : ['GFG', 'Geeks', 'best', 'FOr', 'all', 'GEEKS']
Strings with same case : ['GFG', 'best', 'all', 'GEEKS']

Time complexity: O(N), where n is the length of the ‘test_list’
Auxiliary space: O(M), where m is the number of elements that satisfy the condition, i.e., all lowercase or all uppercase characters.

Method 7: Using ASCII values

 step-by-step algorithm for the approach:

  1. Initialize an empty list res to store the result.
  2. Iterate through each string in the input list test_list.
  3. For each string, check if all characters in the string are either uppercase or lowercase.
  4. If the above condition is true, append the string to the res list.
  5. After iterating through all the strings, print the res list.

Python3




# Define the input list
test_list = ["GFG", "Geeks", "best", "FOr", "all", "GEEKS"]
 
# Initialize an empty list for the output strings with same case
res = []
 
# Iterate through each string in the input list
for string in test_list:
    # Check if all characters in the string are uppercase or lowercase
    if all(65 <= ord(c) <= 90 for c in string) or all(97 <= ord(c) <= 122 for c in string):
        # If all characters have the same case, append the string to the result list
        res.append(string)
 
# Print the result list
print("Strings with same case: " + str(res))


Output

Strings with same case: ['GFG', 'best', 'all', 'GEEKS']

Time Complexity: O(n*k)
Auxiliary Space :O(m)

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