Python – Check if Splits are equal
Last Updated :
14 Mar, 2023
Given String separated by delim, check if all splits are similar.
Input : ’45#45#45′, delim = ‘#’ Output : True Explanation : All equal to 45. Input : ‘4@5@5’, delim = ‘@’ Output : False Explanation : 1st segment equal to 4, rest 5.
Method #1 : Using set() + len() + split()
In this, we perform split to get elements in list format, then convert to set, duplicates are removed, and check for len == 1, confirms all elements are same.
Python3
test_str = '45# 45# 45# 45# 45'
print ( "The original string is : " + str (test_str))
splt_chr = "#"
res = len ( list ( set (test_str.split(splt_chr)))) = = 1
print ( "Are all splits equal ? : " + str (res))
|
Output
The original string is : 45#45#45#45#45
Are all splits equal ? : True
Time complexity: O(n), where n is the length of the test_list. The set() + len() + split() takes O(n) time
Auxiliary Space: O(1), extra constant space is required
Method #2 : Using split() + all()
In this, we perform task of checking for all elements equal using all().
Python3
test_str = '45# 45# 45# 45# 45'
print ( "The original string is : " + str (test_str))
splt_chr = "#"
new_list = test_str.split(splt_chr)
res = all (ele = = new_list[ 0 ] for ele in new_list)
print ( "Are all splits equal ? : " + str (res))
|
Output
The original string is : 45#45#45#45#45
Are all splits equal ? : True
Share your thoughts in the comments
Please Login to comment...