0

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]

1
  • 5
    It doesn't execute. You can't apply the modulus operator to a list and Python will tell you that with a TypeError exception. Commented May 19, 2010 at 11:54

4 Answers 4

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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'

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.