开发者

logical operators evaluation in return statement in python

开发者 https://www.devze.com 2022-12-30 16:06 出处:网络
How does this ex开发者_StackOverflowecute? def f(x): return x>0 and (x%2)+f(x/2) or 0 x is an array, for instance: [1, 1, 1, 3]This code is broken. For starters, x>0 is always true. But x%2 a

How does this ex开发者_StackOverflowecute?

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

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


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


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. 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


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) ...

0

精彩评论

暂无评论...
验证码 换一张
取 消