這是如何執行的?邏輯運算符評估在python中返回statemnet
def f(x):
return x>0 and (x%2)+f(x/2) or 0
x
是一個數組,例如:[1, 1, 1, 3]
謝謝。
這是如何執行的?邏輯運算符評估在python中返回statemnet
def f(x):
return x>0 and (x%2)+f(x/2) or 0
x
是一個數組,例如:[1, 1, 1, 3]
謝謝。
您的意思是?
$ 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'
評估return
聲明與任何其他地方的評估沒有區別。如果x
是一個列表,這整個事情沒有意義,並提出TypeError
。 x
應該是一個數字,這個工作。
如果x
是一個數字,將工作方式如下:
x>0
聲明True
回報(x%2)+f(x/2)
一部分。其中,當然,遞歸無限False
回報0
這段代碼被打破。對於初學者,x>0
總是如此。但是x%2
和x/2
收益類型錯誤。
該函數以數字x的二進制形式遞歸地計算1的數目。
每次該函數將最低位(1或0)與最後一位數字的位數相加(除以2就像向右移位1),或者如果沒有更多位位。
例如: 該函數將5返回2作爲輸入(5是二進制101) 該函數將13返回3作爲輸入(13是二進制1101) ...
它不執行。您不能將模運算符應用於列表,並且Python會通過TypeError異常告訴您。 – msw 2010-05-19 11:54:39