Checking if two strings are permutations of each other in Python

前端 未结 22 2510
旧时难觅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:26

    This is a PHP function I wrote about a week ago which checks if two words are anagrams. How would this compare (if implemented the same in python) to the other methods suggested? Comments?

    public function is_anagram($word1, $word2) {
        $letters1 = str_split($word1);
        $letters2 = str_split($word2);
        if (count($letters1) == count($letters2)) {
            foreach ($letters1 as $letter) {
                $index = array_search($letter, $letters2);
                if ($index !== false) {
                    unset($letters2[$index]);
                }
                else { return false; }
            }
            return true;
        }
        return false;        
    }
    

    Here's a literal translation to Python of the PHP version (by JFS):

    def is_anagram(word1, word2):
        letters2 = list(word2)
        if len(word1) == len(word2):
           for letter in word1:
               try:
                   del letters2[letters2.index(letter)]
               except ValueError:
                   return False               
           return True
        return False
    

    Comments:

        1. The algorithm is O(N**2). Compare it to @namin's version (it is O(N)).
        2. The multiple returns in the function look horrible.
    

提交回复
热议问题