Checking if two strings are permutations of each other in Python

前端 未结 22 2486
旧时难觅i
旧时难觅i 2020-12-08 16:04

I\'m checking if two strings a and b are permutations of each other, and I\'m wondering what the ideal way to do this is in Python. From the Zen of

22条回答
  •  鱼传尺愫
    2020-12-08 16:31

    Your second example won't actually work:

    all(a.count(char) == b.count(char) for char in a)
    

    will only work if b does not contain extra characters not in a. It also does duplicate work if the characters in string a repeat.

    If you want to know whether two strings are permutations of the same unique characters, just do:

    set(a) == set(b)
    

    To correct your second example:

    all(str1.count(char) == str2.count(char) for char in set(a) | set(b))
    

    set() objects overload the bitwise OR operator so that it will evaluate to the union of both sets. This will make sure that you will loop over all the characters of both strings once for each character only.

    That said, the sorted() method is much simpler and more intuitive, and would be what I would use.

提交回复
热议问题