Open In App

Python | Test if string is subset of another

Last Updated : 03 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with strings, we can have a problem in which we need to test if a string is a subsequence of another. This can have possible application in many domains including data science and day-day programming. Lets discuss certain ways in which this task can be performed. 

Method #1: Using all() This is one of the by which we can solve this problem. In this, we employ all() to check if all the characters of one string are present in another. 

Python3




# Python3 code to demonstrate working of
# Test if string is subset of another
# Using all()
 
# initializing strings
test_str1 = "geeksforgeeks"
test_str2 = "gfks"
 
# printing original string
print("The original string is : " + test_str1)
 
# Test if string is subset of another
# Using all()
res = all(ele in test_str1 for ele in test_str2)
 
# printing result
print("Does string contains all the characters of other list? : " + str(res))


Output : 

The original string is : geeksforgeeks
Does string contains all the characters of other list? : True

Time complexity: O(m*n), where m is the length of the first string and n is the length of the second string.
Auxiliary space: O(1), because it only uses a few variables (test_str1, test_str2, res, and ele) that do not depend on the size of the input strings. 

Method #2: Using issubset() Using an inbuilt function is one of the ways in which this task can be performed. In this, we just employ the function and it returns the result after internal processing. 

Python3




# Python3 code to demonstrate working of
# Test if string is subset of another
# Using issubset()
 
# initializing strings
test_str1 = "geeksforgeeks"
test_str2 = "gfks"
 
# printing original string
print("The original string is : " + test_str1)
 
# Test if string is subset of another
# Using issubset()
res = set(test_str2).issubset(test_str1)
 
# printing result
print("Does string contains all the characters of other list? : " + str(res))


Output : 

The original string is : geeksforgeeks
Does string contains all the characters of other list? : True

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

Method#3: Using Recursive method.

  • Initialize an empty set called set1
  • Loop through each character in test_str1
    • Add the character to set1
  • Loop through each character in test_str2
    • If the character is not in set1, return False
    • If all characters in test_str2 are in set1, return True

Python3




def is_subset(test_str1, test_str2):
    if not test_str2:
        return True
    if not test_str1:
        return False
    if test_str1[0] == test_str2[0]:
        return is_subset(test_str1[1:], test_str2[1:])
    return is_subset(test_str1[1:], test_str2)
 
 
# initializing strings
test_str1 = "geeksforgeeks"
test_str2 = "gfks"
 
# printing original string
print("The original string is : " + test_str1)
 
# Test if string is subset of another
# Using recursive function
res = is_subset(test_str1, test_str2)
 
# printing result
print("Does string contains all the characters of other list? : " + str(res))
# this code contributed by tvsk


Output

The original string is : geeksforgeeks
Does string contains all the characters of other list? : True

Time Complexity: O(m*n), where m and n are the lengths of the input strings test_str1 and test_str2, respectively. This is because the function recursively checks each character of test_str2 against each character of test_str1, and in the worst case, all characters of both strings will be checked.
Auxiliary Space: O(m*n), as each recursive call creates a new slice of the input strings. Therefore, if the input strings are very long, the function will use a lot of memory due to the recursive calls.

Method#4:  Using the ‘filter’ function and the ‘len’ function: 

  • Initialize the strings test_str1 and test_str2.
  • Print the original value of test_str1.
  • Use filter() and lambda to create a new list that only contains characters from test_str2 that are also in test_str1.
  • Convert the filtered list to a normal list and check if its length is equal to the length of test_str2.
  • Print the result.

Python3




# Python3 code to demonstrate working of
# Test if string is subset of another
# Using filter() and lambda
 
# initializing strings
test_str1 = "geeksforgeeks"
test_str2 = "gfks"
 
# printing original string
print("The original string is : " + test_str1)
 
# Test if string is subset of another
# Using filter() and lambda
 
# Use filter() and lambda to generate a new list of characters from test_str2
# that are also in test_str1, and then check if the length of that list
# is equal to the length of test_str2
result = len(test_str2) == len(list(filter(lambda c: c in test_str1, test_str2)))
 
# printing result
print("Does string contains all the characters of other list? : " + str(result))
#This code is contributed by Jyothi pinjala


Output

The original string is : geeksforgeeks
Does string contains all the characters of other list? : True

Time complexity : O(n), where n is the length of the shorter string between test_str1 and test_str2. This is because the filter() function needs to iterate through test_str2 to check if each character is also in test_str1.
Auxiliary space : O(n), where n is the length of the shorter string between test_str1 and test_str2. This is because the filter() function creates a new list containing at most n characters, and the list() function also creates a new list containing those n characters. The len() function and boolean comparison also take constant space.

Method#5: Using Counter function

Step-by-step approach:

  • Initialize two strings test_str1 and test_str2.
  • Print the original string.
  • Use all() method to test if string test_str2 is a subset of string test_str1.
  • Store the result in the variable res.
  • Print the final result.

Python3




# importing Counter from collections module
from collections import Counter
 
# initializing strings
test_str1 = "geeksforgeeks"
test_str2 = "gfks"
 
# printing original string
print("The original string is : " + test_str1)
 
# Test if string is subset of another
# Using Counter() function
count1 = Counter(test_str1)
count2 = Counter(test_str2)
res = not bool(count2 - count1)
 
# printing result
print("Does string contains all the characters of other list? : " + str(res))
#This code is contributed by Vinay Pinjala.


Output

The original string is : geeksforgeeks
Does string contains all the characters of other list? : True

Time Complexity: O(n*m), where n is the length of the string test_str1 and m is the length of the string test_str2. This is because we need to check if each character of test_str2 is present in test_str1.
Auxiliary Space: O(1), as we are not using any additional data structures and are only storing boolean values in a single variable res.

Method#6: Using reduce() function with lambda function:

Algorithm:

  1. Import the reduce function from functools module.
  2. Define the is_subset function that takes two string arguments, str1 and str2.
  3. In the is_subset function, use the reduce function to apply a logical AND operation to all the elements of the sequence.
  4. Use the map function to apply a lambda function that checks if each character in str2 is in str1.
  5. Return the result of reduce and map as the output of the function.
  6. Define the test_str1 and test_str2 strings.
  7. Call the is_subset function and pass test_str1 and test_str2 as arguments.
  8. Print the result.

Python3




from functools import reduce
 
def is_subset(str1, str2):
  return reduce(lambda a, b: a and b, map(lambda c: c in str1, str2))
 
# Example usage:
test_str1 = "geeksforgeeks"
test_str2 = "gfks"
# printing original string
print("The original string is : " + test_str1)
print(is_subset(test_str1, test_str2))
#This code is contributed by Rayudu


Output

The original string is : geeksforgeeks
True

Time complexity:
The time complexity of the is_subset function is O(n), where n is the length of str2. The map function takes O(n) time to create a new list of Boolean values, and the reduce function takes O(n) time to compute the final result.

Space complexity:
The space complexity of the is_subset function is also O(n), where n is the length of str2. The map function creates a new list of Boolean values, which requires O(n) space, and the reduce function requires O(1) space.
 



Similar Reads

SymPy | Subset.subset() in Python
Subset.subset() : subset() is a sympy Python library function that returns the subset represented by the current instance. Syntax : sympy.combinatorics.subset.Subset.subset() Return : the subset represented by the current instance. Code #1 : subset() Example # Python code explaining # SymPy.Subset.subset() # importing SymPy libraries from sympy.com
1 min read
Python | Check if a nested list is a subset of another nested list
Given two lists list1 and list2, check if list2 is a subset of list1 and return True or False accordingly. Examples: Input : list1 = [[2, 3, 1], [4, 5], [6, 8]] list2 = [[4, 5], [6, 8]] Output : True Input : list1 = [['a', 'b'], ['e'], ['c', 'd']] list2 = [['g']] Output : False Let's discuss few approaches to solve the problem. Approach #1 : Naive
7 min read
Execute a Subset of Test Suite in Pytest
A testing framework in Python that is used to write API test cases is called Pytest. There are some circumstances in which the user doesn't want to execute all the test suites, but want to execute only certain test cases. In such instances, you can run test suites based on substring matching of test names or on the markers applied. Execute a Subset
3 min read
Python | Sorting string using order defined by another string
Given two strings (of lowercase letters), a pattern and a string. The task is to sort string according to the order defined by pattern and return the reverse of it. It may be assumed that pattern has all characters of the string and all characters in pattern appear only once. Examples: Input : pat = "asbcklfdmegnot", str = "eksge" Output : str = "g
2 min read
Check if a string can be formed from another string by at most X circular clockwise shifts
Given an integer X and two strings S1 and S2, the task is to check that string S1 can be converted to the string S2 by shifting characters circular clockwise atmost X times. Input: S1 = "abcd", S2 = "dddd", X = 3 Output: Yes Explanation: Given string S1 can be converted to string S2 as- Character "a" - Shift 3 times - "d" Character "b" - Shift 2 ti
7 min read
Sum of frequencies of characters of a string present in another string
Given two strings S1 and S2 of lengths M and N respectively, the task is to calculate the sum of the frequencies of the characters of string S1 in the string S2. Examples: Input: S1 = "pPKf", S2 = "KKKttsdppfP"Output: 7Explanation:The character 'p' occurs twice in the string S2.The character 'P' occurs once in the string S2.The character 'K' occurs
5 min read
Python3 Program to Check if a string can be formed from another string by at most X circular clockwise shifts
Given an integer X and two strings S1 and S2, the task is to check that string S1 can be converted to the string S2 by shifting characters circular clockwise atmost X times. Input: S1 = "abcd", S2 = "dddd", X = 3 Output: Yes Explanation: Given string S1 can be converted to string S2 as- Character "a" - Shift 3 times - "d" Character "b" - Shift 2 ti
3 min read
Python3 Program for Check if a string can be obtained by rotating another string d places
Given two strings str1 and str2 and an integer d, the task is to check whether str2 can be obtained by rotating str1 by d places (either to the left or to the right). Examples: Input: str1 = "abcdefg", str2 = "cdefgab", d = 2 Output: Yes Rotate str1 2 places to the left. Input: str1 = "abcdefg", str2 = "cdfdawb", d = 6 Output: No Approach: An appro
3 min read
Check if a string can be repeated to make another string
Given two strings a and b, the task is to check how many times the string a can be repeated to generate the string b. If b cannot be generated by repeating a then print -1. Examples: Input: a = "geeks", b = "geeksgeeks" Output: 2 "geeks" can be repeated twice to generate "geeksgeeks" Input: a = "df", b = "dfgrt" Output: -1 Recommended: Please try y
9 min read
Python3 Program to Check if a string can be obtained by rotating another string 2 places
Given two strings, the task is to find if a string can be obtained by rotating another string two places. Examples: Input: string1 = "amazon", string2 = "azonam" Output: Yes // rotated anti-clockwiseInput: string1 = "amazon", string2 = "onamaz" Output: Yes // rotated clockwise Asked in: Amazon Interview Recommended: Please solve it on “PRACTICE ” f
2 min read
Practice Tags :