差异检查是否在默认数据中是否有钥匙?

发布于 2025-02-03 07:17:51 字数 282 浏览 2 评论 0原文

假设house是默认数据。

house=defaultdict(int)

用纪念编写递归代码时两个以下的区别有什么区别?

if house[i]:
...

if i in house:
...

认为第二个是正确的方法, 当我尝试使用第一个时,我得到了TLE(超过时间限制),但我不知道为什么。 我想知道为什么第二个是正确的。

Suppose house is defaultdict.

house=defaultdict(int)

What's the difference between below two when writing Recursion Code with Memoization?

if house[i]:
...

and

if i in house:
...

I think the second one is the right way,
and when I tried with the first one, I got TLE(Time Limit Exceed) but I don't know why.
I want to know why the second one is correct.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

泪之魂 2025-02-10 07:17:51

前者有两个问题:首先是,如果相应的密钥不存在,它将在字典中创建一个键值对,然后返回0,这在判断中是有效的:

>>> house = defaultdict(int)
>>> if house[0]: print('hello')
...
>>> house
defaultdict(<class 'int'>, {0: 0})

第二个问题是,如果键已经存在,但是相应的值为0或其他真实价值为false的值,判断将是错误的:

>>> house[1] = 0
>>> if house[1]: print('hello')
...
>>> 

The former has two problems: first is if the corresponding key does not exist, it will create a key value pair in the dictionary, and then return 0, which is valid in judgment:

>>> house = defaultdict(int)
>>> if house[0]: print('hello')
...
>>> house
defaultdict(<class 'int'>, {0: 0})

The second problem is that if the key already exists, but the corresponding value is 0 or other value which truth value is false, the judgment will be wrong:

>>> house[1] = 0
>>> if house[1]: print('hello')
...
>>> 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文