if I have 2 strings like:
a = "hello"
b = "olhel"
I want to use a regular expression (or something else?) to see if the two strings contain the same letters. In my example a would = b because they have the same letters. How can this be achieved?
a = "hello"
b = "olhel"
print sorted(a) == sorted(b)
An O(n) algorithm is to create a dictionary of counts of each letter and then compare the dictionaries.
In Python 2.7 or newer this can be done using collections.Counter:
>>> from collections import Counter
>>> Counter('hello') == Counter('olhel')
True
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