我試圖編寫一個函數bin_to_dec(s)
,它接收一個二進制數的字符串並將其轉換爲相應的十進制數/整數。Python中的封閉函數
我知道有可能建立在這種轉換方式,但我試圖通過遞歸來實現它。這是我迄今編程的內容
我不斷收到內存錯誤。我如何編輯我的最後陳述來完成這項工作?
我試圖編寫一個函數bin_to_dec(s)
,它接收一個二進制數的字符串並將其轉換爲相應的十進制數/整數。Python中的封閉函數
我知道有可能建立在這種轉換方式,但我試圖通過遞歸來實現它。這是我迄今編程的內容
我不斷收到內存錯誤。我如何編輯我的最後陳述來完成這項工作?
我會避免遞歸,它不是你想要做的事情所必需的。我的東西去像
def binToDec(s):
total = 0
for index, value in enumerate(s[::-1]):
total += int(value) * 2**index
return total
>>> binToDec('1100')
12
同樣的想法,用列表比較:
def binToDec(s):
return sum(int(value) * 2**index for index,value in enumerate(s[::-1]))
如果你真的想遞歸地做到這一點
def binToDec(s):
if len(s) == 1:
return int(s)
else:
return binToDec(s[-1]) + 2*binToDec(s[:-1])
無論如何,您可以通過檢查它是否爲零來節省昂貴的''**''。 – aruisdante 2014-10-10 16:40:28
嘿,我使用python,從來沒有見過這種語法'[: - 1]',你會介意點一些源?謝謝。 – joaoricardo000 2014-10-10 16:41:39
它被稱爲[切片](https://docs.python.org/2/tutorial/introduction.html)。語法是''[start:stop:step]'',其中一個空值被假定爲''[0:len(list):1]''。請注意,* stop *是排他性的,因此''[0:2]''會讓您獲得前兩個元素,而不是前三個元素。 – aruisdante 2014-10-10 16:42:48
import math
def bin_to_dec(s):
if s == '0':
return 0
elif s == '1':
return 1
elif s[0] == '0':
return bin_to_dec(s[1:])
else:
return int(math.pow(2, len(s) - 1)) + (bin_to_dec(s[1:]))
我不確定。這工作,但需要數學庫。 – gregpaton08 2014-10-10 17:07:56
這裏有一個較短(按行)基於@PeterPeiGuo的遞歸版本:
def bin_to_dec(s):
return int(s[-1]) + (len(s)>1 and 2*(bin_to_dec(s[:-1])))
我覺得他在這裏弄得有些變量名.... – aruisdante 2014-10-10 16:37:42
遞歸通常意味着你從什麼地方調用函數內部本身 – 2014-10-10 16:37:44
我不知道爲什麼你認爲你需要成倍的單曲結果[0] '在這裏2點;最低有效位是0或1,而不是0或2. – 2014-10-10 16:38:02