查看: 10015| 回复: 28
跳转到指定楼层
上一主题 下一主题
收起左侧

[学Python/Perl] 在leetcode答案里写self代表什么?????????????

 
全局:

注册一亩三分地论坛,查看更多干货!

您需要 登录 才可以下载或查看附件。没有帐号?注册账号

x
本帖最后由 ATPtennis 于 2021-12-24 22:11 编辑

比如一道题,leetcode一开始给了个def(self, n):之类的,
然后咱们在下面写答案。

如果我写self.n = n,这和我定义一个new_n = n有什么区别呢?

还有,比如定义个graph,和self.graph这俩有什么区别?

我知道如果咱们定义新函数,平行写,调用的时候需要用self。这里我问的是,咱们什么都不新定义,就在leetcode def下面写答案,
第一行我就写graph = ...和self.graph = ...有什么区别?

这问题是由1494 parallel courses ii引申的。代码如下。
from itertools import combinations # for picking k of n
class Solution:
    @lru_cache(None) # caching for faster lookups
    def recurse(self, mask, in_degrees):
        # if all the bits are 0, we have taken all the courses
        if not mask: return 0

        # all the nodes that *can* be taken now, following both the properties
        nodes = [i for i in range(self.n) if mask & 1 << i and in_degrees == 0]

      
  ans = float('inf')
        # enumerating all the possible combinations
        for k_nodes in combinations(nodes, min(self.k, len(nodes))):
            new_mask, new_in_degrees = mask, list(in_degrees)

            # updating what would happen to new_mask and new_in_degrees
            # if we considered the nodes in k_nodes
            for node in k_nodes:
                # since we know the bit is set, we un-set this bit, to mark it "considered"
                new_mask ^= 1 << node
                # updating each of the in-degrees, since the "parents" have been taken away
                for child in self.graph[node]:
                    new_in_degrees[child] -= 1

            # the heart of recursion
            # note the +1!
            ans = min(ans, 1+self.recurse(new_mask, tuple(new_in_degrees)))
        return ans

    def minNumberOfSemesters(self, n: int, relations: List[List[int]], k: int) -> int:
        # saving n and k for later use
        self.n = n
        self.k = k
        in_degrees = [0]*self.n
        # graph layout remains the same, although the in_degrees change.
        # This allows us to keep graph as self.graph
        # instead of passing it over and over.
        self.graph = defaultdict(list)
        for prev_course, next_course in relations:
            # remember, its 0-indexed now!
            in_degrees[next_course - 1] += 1
            self.graph[prev_course - 1].append(next_course - 1)

        # start with all the bits set
        return self.recurse((1 << self.n) - 1, tuple(in_degrees))


我个人习惯不喜欢平行写定义,我喜欢把定义写到leetcode定义里面。当我把第一个def写到第二个里面时,然后删除self,提示不能哈希的列表

评分

参与人数 1大米 +1 收起 理由
14417335 + 1 欢迎来一亩三分地论坛!

查看全部评分


上一篇:为啥我会觉得形如滑动窗口的题目相比其他题目更难
下一篇:leetcode做题时右边那个notes 怎么移除呀
推荐
MikeYYYT 2021-12-25 05:06:15 | 只看该作者
全局:
建議先學好python再開始刷題...

评分

参与人数 4大米 +4 收起 理由
putaoganshaqima + 1 给你点个赞!
zeanzhou + 1 给你点个赞!
unclewillie + 1 赞一个
qlotem + 1 给你点个赞!

查看全部评分

回复

使用道具 举报

全局:
我很惊讶能在破地里看到这种问题,小红书都不如了吗…
回复

使用道具 举报

全局:
python基础,self是一个class的attribute,会存在instance中。你直接newn=n也没啥,就是name space不能跨越class的function

评分

参与人数 1大米 +1 收起 理由
14417335 + 1 给你点个赞!

查看全部评分

回复

使用道具 举报

🔗
 楼主| ATPtennis 2021-12-25 05:30:57 | 只看该作者
全局:
SnowCSWG 发表于 2021-12-24 22:04
python基础,self是一个class的attribute,会存在instance中。你直接newn=n也没啥,就是name space不能跨越 ...

问题中代码我什么都没变,就是把第一个函数写到第二个函数里面,删除所有self,然后报错
TypeError: unhashable type: 'list'
    ret = Solution().minNumberOfSemesters(param_1, param_2, param_3)
Line 96 in _driver (Solution.py)
    _driver()
Line 107 in <module> (Solution.py)

代码如下,不知道这里面哪个self是不是不能删????

from itertools import combinations # for picking k of n
class Solution:
    @lru_cache(None) # caching for faster lookups
   
   
    def minNumberOfSemesters(self, n: int, relations: List[List[int]], k: int) -> int:
              
        # saving n and k for later use        
        in_degrees = [0]*n
        # graph layout remains the same, although the in_degrees change.
        # This allows us to keep graph as self.graph
        # instead of passing it over and over.
        graph = defaultdict(list)
        for prev_course, next_course in relations:
            # remember, its 0-indexed now!
            in_degrees[next_course - 1] += 1
            graph[prev_course - 1].append(next_course - 1)
        
        
        def recurse(mask, in_degrees):
            # if all the bits are 0, we have taken all the courses
            if not mask: return 0

            # all the nodes that *can* be taken now, following both the properties
            nodes = [i for i in range(n) if mask & 1 << i and in_degrees == 0]

            
ans = float('inf')
            # enumerating all the possible combinations
            for k_nodes in combinations(nodes, min(k, len(nodes))):
                new_mask, new_in_degrees = mask, list(in_degrees)

                # updating what would happen to new_mask and new_in_degrees
                # if we considered the nodes in k_nodes
                for node in k_nodes:
                    # since we know the bit is set, we un-set this bit, to mark it "considered"
                    new_mask ^= 1 << node
                    # updating each of the in-degrees, since the "parents" have been taken away
                    for child in graph[node]:
                        new_in_degrees[child] -= 1

                # the heart of recursion
                # note the +1!
                ans = min(ans, 1+recurse(new_mask, tuple(new_in_degrees)))
            return ans
        
        # start with all the bits set
        return recurse((1 << n) - 1, tuple(in_degrees))

回复

使用道具 举报

全局:
变量声明里没self好像会影响递归的调用。。ps你为啥一定要把那个self删了啊
回复

使用道具 举报

🔗
 楼主| ATPtennis 2021-12-25 05:43:20 | 只看该作者
全局:
本帖最后由 ATPtennis 于 2021-12-24 22:44 编辑
lancevi96 发表于 2021-12-24 22:37
变量声明里没self好像会影响递归的调用。。ps你为啥一定要把那个self删了啊

我原来最开始接触dfs时写习惯了就把dfs一直写在leetcode大定义里面,慢慢就不想带着self了,除非极端迫不得已非得写self才写。比如两个函数平行写,我一般都写到一个里面。
受累再帮我看一下我上个回复,是没办法把第一个def写到第二个里面了么。
TypeError: unhashable type: 'list'
    ret = Solution().minNumberOfSemesters(param_1, param_2, param_3)
Line 96 in _driver (Solution.py)
    _driver()
Line 107 in <module> (Solution.py)
回复

使用道具 举报

全局:
我想是本身class的聲明,你可以用self調用自身函數,members….emmmm

补充内容 (2021-12-25 06:38 +08:00):
把class封装起来,self不就有用了
回复

使用道具 举报

全局:
这不单单是Python是OOP的概念吧,你把class当class,def是function,完了很多题例如BFS有上下左右(虽然Python能写外面),或者一些数据结构题有自带变量,然后想象成都是new出来跑test case的就很清楚了
回复

使用道具 举报

🔗
Pizi-G 2021-12-25 07:13:16 | 只看该作者
全局:
我觉得你是没懂 python 里的 OOP/class 是怎么回事...

你说的 "不喜欢平行写定义", 你的意思是不喜欢平行列 def, 而是喜欢写进同一个里?
- 从代码功能上, 确实两种都能做同一件事情, 但是把每个部分写分离, 就是为了 maintenance 和 readability. 就算到 extreme, 你所有东西全都只在一个 def 里, class 也不要, 也能完成任何 OOP 能做的最终结果 (也就是被叫做 spaghetti code). 但是基本是维护的噩梦.
- 至于哪里用 self, 哪里不用, 为什么报错. 你可以好好再看看 python 的 class, scope 等内容. 比如你可以看看这些例子你在跑之前能不能知道为什么哪些会报错 https://trinket.io/python/0dcd51fa1d

评分

参与人数 3大米 +8 收起 理由
rocket_science + 1 赞一个
JeanWu + 5 很有用的信息!
14417335 + 2 给你点个赞!

查看全部评分

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表