[英]logical operators evaluation in return statement in python
如何執行?
def f(x):
return x>0 and (x%2)+f(x/2) or 0
x
是一個數組,例如: [1, 1, 1, 3]
該代碼已損壞。 對於初學者, x>0
始終為true。 但是x%2
和x/2
產生類型錯誤。
你是這個意思嗎
$ 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的二進制形式遞歸計算1的數量。
每次函數相加時,將最低位數(1或0)與一個位數的位數(不含最后一位)相加(除以2就像右移1),如果沒有更多位數則為0。
例如:函數將以2的形式返回5作為輸入(5是101的二進制數)函數將以13的形式返回3作為輸入(13是的1101是二進制的)...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.