Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

match two strings with letters in random order in python

Tags:

python

regex

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?

like image 859
Jack S. Avatar asked Dec 05 '25 15:12

Jack S.


2 Answers

a = "hello"
b = "olhel"
print sorted(a) == sorted(b)
like image 172
Glenn Maynard Avatar answered Dec 07 '25 05:12

Glenn Maynard


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
like image 37
Mark Byers Avatar answered Dec 07 '25 04:12

Mark Byers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!