但是有可用更好的選擇,我假設你正在清除您的基本知識。以下是可選項:
注意:您應該在循環中使用len(value)而不是int(value)。
# 1. When starting the loop from 0 (i.e. i=0). you can use (len(value) - i)th index.'
for i in range (len(value)):
prod = ((int(value[len(value) - i - 1])) * ((2**power)))
ans = prod + ans
prod = 0
power = power + 1
# 2. Python also supports negative indexing, So you may run a loop from -1 to -len(value).
for i in range (-1,-len(value) - 1,-1):
prod = ((int(value[i])) * ((2**power)))
ans = prod + ans
prod = 0
power = power + 1
# 3. You can reverse the whole string in your first step and then loop from 0 to len(value)-1.
value = reversed(value)
for i in range (len(value)):
prod = ((int(value[i])) * ((2**power)))
ans = prod + ans
prod = 0
power = power + 1
但也有在代碼中的一些錯誤(或者可能是缺乏信息)。此代碼僅適用於無符號整數。如果您希望它也可以使用帶符號的數字,則必須考慮2的補碼。 下面是一個非常簡單的代碼與符號數過工作(在需要的情況下):
#convert binary string into decimal value. Works on 2's complement.
def binToDecimal(s):
neg = False
if s[0] == '1':
s = twosComp(s)
neg = True
#compute the decimal value
val = reduce(lambda x,y : int(x)*2+1 if y=='1' else int(x)*2,'0'+s)
#negate the value if the first bit is 1
return -val if neg else val
#return the 2's complement string
def twosComp(s):
s = list(s[::-1])
#take 1's complement
s = ['1' if i=='0' else '0' for i in s]
#take 2's complement
for i in range(len(s)):
if s[i] == '0':
#no carry will be generated in this case, so we break it.
s[i] = '1'
break
else:
s[i]='0'
# return 2's complement string
return ''.join(map(str,s))[::-1]
只是爲了記錄在案,你可以隨時使用'INT(值,基地= 2)'。但是,如果您只是想將其用作練習,則正確的方法是以相反的順序遍歷字符串(而不是索引):'對於反向(值)位:' –
另外,不需要'prod = 0'在你的循環中。 「power + 1」應該是「power = power + 1」或「power + = 1」。或者更好的辦法是,爲了權力,列舉一下(反轉(值)):'而不需要處理遞增。 –
我很感激幫助。但是我對此很陌生,而且我無法準確找到您提供的代碼的位置。 'prod = 0'被刪除,現在'power = power + 1'。雖然我無法找到在哪裏放權力,在枚舉(顛倒(價值)):「這是爲了取代for循環? – AAGW