I need to be able to discern if a string of an arbitrary length, greater than 1 (and only lowercase), has the same set of characters within a base or template string.
For example, take the string "aabc": "azbc" and "aaabc" would be false while "acba" would be true.
Is there a fast way to do this in python without keeping track of all the permutations of the first string and then comparing it to the test string?
To find whether a string has all the same characters. Traverse the whole string from index 1 and check whether that character matches the first character of the string or not. If yes, then match until string size. If no, then break the loop.
Python strings equality can be checked using == operator or __eq__() function. Python strings are case sensitive, so these equality check methods are also case sensitive.
Python String comparison can be performed using equality (==) and comparison (<, >, != , <=, >=) operators. There are no special methods to compare two strings.
Python comparison operators can be used to compare strings in Python. These operators are: equal to ( == ), not equal to ( != ), greater than ( > ), less than ( < ), less than or equal to ( <= ), and greater than or equal to ( >= ).
Sort the two strings and then compare them:
sorted(str1) == sorted(str2)
If the strings might not be the same length, you might want to make sure of that first to save time:
len(str1) == len(str2) and sorted(str1) == sorted(str2)
This is the O(n)
solution
from collections import Counter
Counter(str1) == Counter(str2)
But the O(n * log n)
solution using sorted
is likely faster for sensible values of n
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With