python 3.x - Why am I not getting an expected output using logical operators and indexing? -
i having trouble achieving expected output. trying create byte adder using logical operators such and, xor , or. have taken minimal code required reproduce problem out of code, assume finalfirstvalue = "1010"
, finalsecondvalue = "0101"
.
secondvalueindex = (len(finalsecondvalue) - 1) carry, finalans = false, [] in range(-1, -len(finalfirstvalue) - 1, -1): andone = (bool(finalfirstvalue[i])) & (bool(finalsecondvalue[secondvalueindex])) xorone = (bool(finalfirstvalue[i])) ^ (bool(finalsecondvalue[secondvalueindex])) andtwo = (bool(carry)) & (bool(xorone)) xortwo = (bool(carry)) ^ (bool(xorone)) orone = (bool(andone)) | (bool(andtwo)) carry = (bool(orone)) finalans.append(xortwo) secondvalueindex -= 1 answer = ''.join(str(e) e in finalans) print (answer)
actual output: falsetruetruetrue
expected output: truetruetruetrue
the code follows change zeroes , ones.
because missing single boolean feel issue indexing. although i've played around bit , not had luck.
i need carry out these operations on 2 variables mentioned @ start, right elements, , move left 1 next loop , on.
first mistake representing binary numbers string values.
finalfirstvalue = "1010"
finalsecondvalue = "0101"
secondvalueindex = (len(finalsecondvalue) - 1)
==
3
so in second loop result as
(finalsecondvalue[secondvalueindex])
==
'0'
if check in idle
>>> bool('0') true >>>
because '0'
not actual 0 non-empty string return true.
you need cast result int
before checking them bool
like this
(bool(int(finalsecondvalue[secondvalueindex])))
edit 2 adding variable lenghts
full adder verification using bin()
function
a="011101" b="011110" if a>b: b=b.zfill(len(a)) if a<b: a=a.zfill(len(b)) finalfirstvalue = finalsecondvalue = b carry, finalans = 0, [] secondvalueindex = (len(finalsecondvalue)) in reversed(range(0, len(finalfirstvalue))): xorone = (bool(int(finalfirstvalue[i]))) ^ (bool(int(finalsecondvalue[i]))) andone = (bool(int(finalfirstvalue[i]))) & (bool(int(finalsecondvalue[i]))) xortwo = (carry) ^ (xorone) andtwo = (carry) & (xorone) orone = (andone) | (andtwo) carry = (orone) finalans.append(xortwo) finalans.reverse() answer=(''.join(str(e) e in finalans)) print(str(carry)+answer) print(bin(int(a,2) + int(b,2))) #verification
Comments
Post a Comment