开发者

match two strings with letters in random order in python

开发者 https://www.devze.com 2023-01-18 07:37 出处:网络
if I have 2 strin开发者_如何转开发gs 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

if I have 2 strin开发者_如何转开发gs 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
0

精彩评论

暂无评论...
验证码 换一张
取 消