Open In App

Python – Extract Strings with Successive Alphabets in Alphabetical Order

Given a string list, extract list which has any succession of characters as they occur in alphabetical order.

Input : test_list = [‘gfg’, ‘ij’, ‘best’, ‘for’, ‘geeks’] 
Output : [‘ij’, ‘gfg’, ‘best’] 
Explanation : i-j, f-g, s-t are consecutive pairs.



Input : test_list = [‘gf1g’, ‘in’, ‘besht’, ‘for’, ‘geeks’] 
Output : [] 
Explanation : No consecutive pairs. 

Method #1 : Using ord() + loop



In this, we check for each string if it contains and character with is the alphabetic successor to its preceding character, ASCII conversion is done using ord().




# Python3 code to demonstrate working of
# Extract Strings with successive Alphabets
# Using ord() + loop
 
# initializing string list
test_list = ['gfg', 'is', 'best', 'for', 'geeks']
 
# printing original list
print("The original list is : " + str(test_list))
 
res = []
for sub in test_list:
     
    # iterating for string
    for idx in range(len(sub) - 1):
         
        # checking for alphabetic consecution
        if ord(sub[idx]) == ord(sub[idx + 1]) - 1:
            res.append(sub)
            break
     
# printing result
print("Strings with alphabetic consecution : " + str(res))

Output
The original list is : ['gfg', 'is', 'best', 'for', 'geeks']
Strings with alphabetic consecution : ['gfg', 'best']

Time Complexity: O(n2)

Space Complexity: O(n)

Method #2 : Using any() + filter() + lambda

In this, we check for any succession using any(), and task of filtering is done using filter() and lambda function.




# Python3 code to demonstrate working of
# Extract Strings with successive Alphabets
# Using any() + filter() + lambda
 
# initializing string list
test_list = ['gfg', 'is', 'best', 'for', 'geeks']
 
# printing original list
print("The original list is : " + str(test_list))
 
# filtering using filter, and checking for any substring using any()
res = list(filter(lambda sub: any(ord(sub[idx]) == ord(
    sub[idx + 1]) - 1 for idx in range(len(sub) - 1)), test_list))
 
# printing result
print("Strings with alphabetic consecution : " + str(res))

Output
The original list is : ['gfg', 'is', 'best', 'for', 'geeks']
Strings with alphabetic consecution : ['gfg', 'best']

Time Complexity: O(n2)

Space Complexity: O(n)

Method #3: Using recursion 

In this method, the has_consecutive_alphabets() function checks if a string has consecutive alphabets by comparing the ASCII values of adjacent characters. 

Algorithm: 

Below is the code for the above approach. 




# Define the function to check if a string contains consecutive alphabets
def has_consecutive_alphabets(s):
    if len(s) <= 1:
        return False
    if ord(s[0]) == ord(s[1]) - 1:
        return True
    return has_consecutive_alphabets(s[1:])
 
# Initialize the list of strings
test_list = ['gfg', 'is', 'best', 'for', 'geeks']
 
# Print the original list
print("The original list is : " + str(test_list))
 
# Filter the list for strings containing consecutive alphabets using the recursive function
res = list(filter(lambda sub: has_consecutive_alphabets(sub), test_list))
 
# Print the result
print("Strings with alphabetic consecution : " + str(res))

Output
The original list is : ['gfg', 'is', 'best', 'for', 'geeks']
Strings with alphabetic consecution : ['gfg', 'best']

Time Complexity: O(nm), where n is the length of the input list and m is the maximum length of a string in the list.

Auxiliary Space: O(m), which is the maximum depth of the recursion stack.

Method #6: Using itertools.groupby()

Another approach to check for consecutive alphabets in a string is by using the itertools.groupby() function. This function groups consecutive elements that are the same, so we can use it to group consecutive characters that are consecutive in ASCII code.

Import the itertools module.
Initialize an empty list to hold the results.
Iterate through each string in the list of strings.
Use itertools.groupby() to group consecutive characters that are consecutive in ASCII code.
Convert each group of characters to a list.
Check if any list has length greater than 1 (i.e., contains consecutive alphabets).
If any list has length greater than 1, append the string to the list of results.
Return the list of results.




import itertools
 
def has_consecutive_alphabets(s):
    for k, g in itertools.groupby(enumerate(s), lambda ix: ix[0] - ord(ix[1])):
        if len(list(g)) > 1:
            return True
    return False
 
def find_strings_with_consecutive_alphabets(lst):
    results = []
    for s in lst:
        if has_consecutive_alphabets(s):
            results.append(s)
    return results
 
test_list = ['gfg', 'is', 'best', 'for', 'geeks']
print("The original list is: " + str(test_list))
res = find_strings_with_consecutive_alphabets(test_list)
print("Strings with alphabetic consecution: " + str(res))

Output
The original list is: ['gfg', 'is', 'best', 'for', 'geeks']
Strings with alphabetic consecution: ['gfg', 'best']

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(k), where k is the number of strings that contain consecutive alphabets (i.e., the length of the results list).


Article Tags :