Reputation: 615
I'm looking for some function where I can compare two string with the exception that the order of the elements no matter. E.g.:
'abc' == 'bca'
True
Does python have some built-in function like this?
Upvotes: 0
Views: 5966
Reputation: 180401
6For smaller strings you could call sorted on both strings:
def is_equal(a, b):
return len(a) == len(b) and sorted(a) == sorted(b)
For sorted(a) == sorted(b)
to be True, both strings must be the same length and have the same characters:
Or use a Counter
dict to count the frequencies if the string lengths are the same:
from collections import Counter
def is_equal(a, b):
return len(a) == len(b) and Counter(a) == Counter(b)
If the strings are different lengths then they cannot be equal, if they are all the chars from a have to be in b and the frequency has to be the same. The solution is O(n)
as opposed to O(n log n)
calling sorted
Upvotes: 2
Reputation: 311188
Strings in python are iterables that return the characters in the string. Like any iterable, they can be wrapped with sorted
. If you compare those wrappers, you'd essentially be comparing whether both strings have the same characters in them, regardless of their original order:
>>> s = 'abc'
>>> t = 'bca'
>>> s == t
False
>>> sorted(s) == sorted(t)
True
Upvotes: 4