python中return语句中的逻辑运算符求值

发布于 2024-09-01 23:34:24 字数 150 浏览 1 评论 0原文

这是如何执行的?

def f(x):
    return x>0 and (x%2)+f(x/2) or 0

x 是一个数组,例如:[1, 1, 1, 3]

How does this execute?

def f(x):
    return x>0 and (x%2)+f(x/2) or 0

x is an array, for instance: [1, 1, 1, 3]

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

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

发布评论

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

评论(4

夏日落 2024-09-08 23:34:32

该函数递归地计算数字 x 的二进制形式中 1 的数量。

每次该函数将最低位(1 或 0)与没有最后一位的数字的位数相加(除以 2 相当于右移 1),如果没有更多位,则将其与 0 相加。

例如:
该函数将返回 2 for 5 作为输入(5 是二进制的 101)
该函数将返回 3,表示 13 作为输入(13 是二进制的 1101)
...

The function recursively counts the number of 1's in the binary form of the number x.

Each time the function adds sums the lowest bit (either 1 or 0) with the bit count of a number without the last bit (dividing by 2 is like shifting right by 1), or with 0 if there are no more bits.

For example:
The function will return 2 for 5 as an input (5 is 101 in binary)
The function will return 3 for 13 as an input (13 is 1101 in binary)
...

迷荒 2024-09-08 23:34:30

return 语句中的求值与任何其他地方的求值没有什么不同。如果x是一个列表,那么整个事情就没有意义并引发TypeErrorx 应该是一个数字才能起作用。

如果x是一个数字,它将按如下方式工作:

  • 评估x>0语句,
  • 如果它是True返回(x%2) +f(x/2) 部分。当然,
  • 如果它是 False 返回 0 则无限递归

evaluation in return statement is no different from evaluation in any other place. if x is a list this whole thing makes no sense and raises TypeError. x should be a numeric for this to work.

If x is a number it would work as follows:

  • evaluate x>0 statement
  • if it was True return (x%2)+f(x/2) part. Which, of course, recurses infinitely
  • if it was False return 0
稳稳的幸福 2024-09-08 23:34:29

你是这个意思吗?

$ python
Python 2.5.5 (r255:77872, Apr 21 2010, 08:40:04) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def f(x):
...     return x>0 and (x%2)+f(x/2) or 0
... 
>>> f([1, 1, 1, 3])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in f
TypeError: unsupported operand type(s) for %: 'list' and 'int'

Did you mean this?

$ python
Python 2.5.5 (r255:77872, Apr 21 2010, 08:40:04) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def f(x):
...     return x>0 and (x%2)+f(x/2) or 0
... 
>>> f([1, 1, 1, 3])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in f
TypeError: unsupported operand type(s) for %: 'list' and 'int'
入画浅相思 2024-09-08 23:34:27

这段代码已损坏。对于初学者来说,x>0 始终为真。但 x%2x/2 会产生类型错误。

This code is broken. For starters, x>0 is always true. But x%2 and x/2 yield type errors.

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