Open In App

Test if String is Subset of Another – Python

Last Updated : 17 Jan, 2025
Comments
Improve
Suggest changes
2 Likes
Like
Report

We are given two strings s1 and s2 and the task is to check whether s2 is a subsequence of s1. A subsequence is a sequence that appears in the same relative order but not necessarily consecutively.

Using all()

In this method we check whether all the characters of s2 are present in s1 by using the all() function and it returns True if all the conditions in the iterable are True


Output
True

Let’s check other methods to achieve the same :

Using issubset()

In this method we convert s2 into a set then check if all characters in s2 are a subset of s1.then utilize the issubset() method of sets to directly determine the inclusion.


Output
True

Using a Recursive Method

In this method we recursively check if each character of s2 exists in s1 in order and reduce both strings step by step in order to do that.


Output
True

Explanation:

  • function is_subset() checks character by character if s2 is a subsequence of s1 recursively.
  • If s2 becomes empty it means all characters were found in s1 and we return True otherwise false is returned.

Using the filter() function and len()

This method uses filter() along with lambda to create a filtered list of characters from s2 that are also in s1, and then checks if the length of this list matches the length of s2.


Output
True

Explanation: filter() function checks each character in s2 to see if it is present in s1 and the len() function verifies if the number of matching characters is the same as the length of s2.

Using the Counter function

This method utilizes the Counter class from the collections module to count the frequency of characters in both strings and then checks if all characters of s2 are present in s1.


Output
True

Explanation

  • Counter class counts the frequency of characters in both s1 and s2 and this creates dictionaries where each key is a character and the value is its frequency in the respective string.
  • Expression count2 - count1 checks if any character in s2 has a greater frequency than in s1 and if the result is an empty dictionary it means s2 is a subsequence of s1 and hence True is returned.


Next Article
Practice Tags :

Similar Reads