1. 程式人生 > >Learning python by leetcode: No.49 Group Anagrams

Learning python by leetcode: No.49 Group Anagrams

contents

題目

leetcode 49 Group Anagrams

code

class Solution:
    def groupAnagrams(self, strs):
        """
        :type strs: List[str]
        :rtype: List[List[str]]
        """
        result = collections.
defaultdict(list) for word in strs: count = [0] *26 for c in word: count[ord(c) - ord('a')] +=1 result[tuple(count)].append(word) return list(result.values())

FBI Warning

In python2 , dict.values() return a copy of the dict list;
However, in python3, dict.values() return view objects

. They provide a dynamic view on the dictionary’s entries, which means that when the dictionary changes, the view reflects these changes.

As a result, you need to encapsulate it into list by list().

details

line 7

defaultdict is a subclass of dict;
defaultdict has default value for the keys (for dict, you the key-value doesn’t exist, throw Keyerror!). You specify the default value by giving a default_factory

( it defaults to None. )
The factory may be function or lambda.

line 12

The key of a dict must be invariable object.
List is a variable object, unsuitable for key, OK with tuple.

不可變物件,該物件所指向的記憶體中的值不能被改變。當改變某個變數時候,由於其所指的值不能被改變,相當於把原來的值複製一份後再改變,這會開闢一個新的地址,變數再指向這個新的地址。
可變物件,該物件所指向的記憶體中的值可以被改變。變數(準確的說是引用)改變後,實際上是其所指的值直接發生改變,並沒有發生複製行為,也沒有開闢新的出地址,通俗點說就是原地改變。
Python中,數值型別(int和float)、字串str、元組tuple都是不可變型別。而列表list、字典dict、集合set是可變型別。