Learning python by leetcode: No.49 Group Anagrams

LeetCode 49题详解
本文详细解析了LeetCode第49题“Group Anagrams”的解决方案,通过使用Python的collections.defaultdict,实现了一个高效且简洁的算法。文章强调了在Python 3中使用dict.values()返回视图对象而非拷贝的特性,以及如何正确处理字典的键值对,避免常见的编程陷阱。

题目

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是可变类型。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值