views:

80

answers:

4

hi,

how does this execute:

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

x is an array ,for instanse,[1, 1, 1, 3]

thank u

A: 

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'
Messa
A: 

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
SilentGhost
A: 

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

Marcelo Cantos
A: 

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

Adam