2014-03-13 45 views
0
decimal = input("Please insert a number: ") 


if decimal > 256: 

print "Value too big!" 


elif decimal < 1: 
    print "Value too small!" 

else: 
    decimal % 2 

binary1 = [] 
binary0 = [] 
if decimal % 2 == 0: 
    binary1.append[decimal] 

else: 
    binary0.append[decimal] 
print binary1 
print binary0 

概念,到目前爲止,我想測試此代碼,它說,在第13行:我的代碼有什麼問題?我無法把握的

TypeError: builtin_function_or_method' object has no attribute __getitem__ .

我不明白爲什麼這是錯的。

我想將十進制數轉換爲二進制。我只想嘗試獲取輸入的第一個值,然後將其存儲在列表中以供使用,然後將其作爲0或1添加到另一個列表中。如果輸入不等於2,則添加一個零。我將如何做到這一點?

回答

5
binary1.append[decimal] 

您試圖從append方法獲取元素,因此引發錯誤。由於它是一個函數或方法,因此您需要使用適當的語法來調用它。

binary1.append(decimal) 

對於其他追加呼叫同上。

+0

同上?謝謝,讓我看看是否有效!謝謝! – Nathaniel

+0

它確實工作! 如果我這樣做是爲了將每個結果分爲2,是否有更快的方法,比如2或3行?我聽說** 2,但不知道,請解釋!你能解釋一下 – Nathaniel

+0

嗎? – Nathaniel

0

迴應你的二進制問題。可以很容易地將你的方式蠻力推向解決方案。這背後的思想是我們將採取任何數字N,然後N減2,最大的功率將小於N.例如。

N = 80

2^6 = 64

在二進制爲1000000。

現在取N這被表示 - 2^6得到16.

查找最大功率2可以應用於小於或等於N.

2^4 = 16

以二進制表示,現在表示爲1010000.

有關實際代碼。

bList = [] 
n = int(raw_input("Enter a number")) 
for i in range(n, 0, -1): # we will start at the number, could be better but I am lazy, obviously 2^n will be greater than N 
    if 2**i <= n: # we see if 2^i will be less than or equal to N 
     bList.append(int("1" + "0" * i)) # this transfers the number into decimal 
     n -= 2**i # subtract the input from what we got to find the next binary number 
     print 2**i 
print sum(bList) # sum the binary together to get final binary answer 
+0

我想你誤會了....我想使一個BINARY到DECIMAL轉換器使用除以2並存儲1和0 ... – Nathaniel

+0

@Nathaniel哎呀。好的,我會在稍後回答這個問題。 – nwalsh

+0

@Nathaniel它在哪裏說你想要二進制到十進制?存儲1和0使得它將十進制轉換爲二進制,這是你在原始文章中試圖做的 – nwalsh