简体   繁体   English

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

[英]logical operators evaluation in return statement in python

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] x是一个数组,例如: [1, 1, 1, 3]

This code is broken. 该代码已损坏。 For starters, x>0 is always true. 对于初学者, x>0始终为true。 But x%2 and x/2 yield type errors. 但是x%2x/2产生类型错误。

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'

evaluation in return statement is no different from evaluation in any other place. return表中的评估与其他地方的评估没有区别。 if x is a list this whole thing makes no sense and raises TypeError . 如果x是一个列表,那么整个事情毫无意义,并引发TypeError x should be a numeric for this to work. x应该是数字才能起作用。

If x is a number it would work as follows: 如果x是一个数字,它将按以下方式工作:

  • evaluate x>0 statement 计算x>0语句
  • if it was True return (x%2)+f(x/2) part. 如果是True返回(x%2)+f(x/2)部分。 Which, of course, recurses infinitely 当然,这无限递归
  • if it was False return 0 如果为False返回0

The function recursively counts the number of 1's in the binary form of the number x. 该函数以数字x的二进制形式递归计算1的数量。

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. 每次函数相加时,将最低位数(1或0)与一个位数的位数(不含最后一位)相加(除以2就像右移1),如果没有更多位数则为0。

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) ... 例如:函数将以2的形式返回5作为输入(5是101的二进制数)函数将以13的形式返回3作为输入(13是的1101是二进制的)...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM