I'd like to do a binary calculation using half-add and full-add, but an error appears below the last while syntax, and the process does not proceed.Please let me know
error messages:
TypeError Traceback (most recent call last)
<ipython-input-30-1544c3673a72>in<module>
39goukei=""
40 while k>=0:
--- >41 ha = int(a(k))
42 fa = int(b(k))
43 A, keta = fa(a, b, x)
TypeError: 'str' object is not callable
code:
from traillets.config.application import logging
def AND(a,b):
A = a * b
return A
def OR(a,b):
if a == 1:
if b == 1:
A = 1
else:
A = 0
def NOT(a):
if a == 1:
A = 0
if a == 0:
A = 1
return A
def ha(a,b):
A1 = OR(a,b)
keta = AND(a,b)
A2 = NOT (keta)
A = AND (A1, A2)
return A, keta
deffa(a,b,x):
A1,keta1 = ha(a,b)
A,keta2 = ha(A1,x)
keta=OR (keta1, keta2)
return A, keta
a = input ("binary number")
b = input ("the binary plus")
k=len(a)
k = k - 1
x = 0
goukei=""
while k>=0:
ha = int(a(k))
fa = int(b(k))
A,keta=fa(a,b,x)
goukei=str(A)+goukei
x = keta
k = k - 1
goukei=str(x)+goukei
print(a, "+", b, "=", gookei)
As a whole, there are about three major mistakes.
Extraction of Elements
while k>=0:
ha = int(a(k))
fa = int(b(k))
A,keta=fa(a,b,x)
a[k]
, b[k]
if you want to take it out
ha
, fa
are used as function names, so they are overwritten.Should be a different variable name fa
should be the previous "extracted value" instead of a
, b
We have made it possible to calculate even if the number of digits a
and b
are different from the corrections pointed out by those who have already answered.You can also fill in 0
to make it the same number of digits before calculating.
def AND(x,y):
return1 if x and else0
defOR(x,y):
return1 if x or else0
def NOT(x):
return1 if not x else0
def ha(x,y):
K = AND(x,y)
A = AND (OR(x,y), NOT(K))
return A,K
deffa(x,y,z):
A1,K1 = ha(x,y)
A2,K2 = ha(A1,z)
K3 = OR (K1, K2)
return A2,K3
a = input("binary a:")
b = input ("binary b:")
k, m = len(a), len(b)
keta = 0
goukei='"
while > 0 or m > 0:
k,m = k-1,m-1
na = 0 if k < 0 else int(a[k])
nb = 0 if m<0 else int(b[m])
ns,keta=fa(na,nb,keta)
goukei=str(ns)+goukei
goukei=('1'if keta else') + goukei
print(f'{a}+{b}={goukei}')
binary a:110011
Binary b: 1110
110011 + 1110 = 1000001
© 2025 OneMinuteCode. All rights reserved.