-1

I need a help of my code, i have make addition of passing two variable of two binary numbers and the answer is incorrect!

in my code

import data as s
s.num
s.demo 
def add_binary_nums(x,y):
        max_len = max(len(x), len(y))

        x = x.zfill(max_len)
        y = y.zfill(max_len)

        result = ''
        carry = 0

        for i in range(max_len-1, -1, -1):
            r = carry
            r += 1 if x[i] == '1' else 0
            r += 1 if y[i] == '1' else 0
            result = ('1' if r % 2 == 1 else '0') + result
            carry = 0 if r < 2 else 1       

        if carry !=0 : result = '1' + result

        return result.zfill(max_len)

print("start here") 
demoo = (add_binary_nums(s.num,s.demo))
print(demoo)

assume the values as num="011000100110111101100010" and demo="001" and the answer of above code is 011000100110111101100110 , and it's wrong answer! when i pass the value like

 num="011000100110111101100010"
   demo="001"

i got the the answer 01111011000010110011101010 .

and fpr passing the value like

print(add_binary_nums('001', '001'))

the result will be 01100010011011110110010 i'm getting 3 different results!!

Any suggestion!

hani
  • 19
  • 6
  • 1
    Why is there a space in `value = '001 '`? – khelwood Jan 08 '20 at 09:16
  • space not effect, i remove the space and the answer is same wrong – hani Jan 08 '20 at 09:19
  • 4
    Really? Because when I removed the space I got the right answer. And your question says that when you tried `add_binary_nums('001', '001')` that **you** got the right answer. That indicates that the space **is** the problem. – khelwood Jan 08 '20 at 09:22
  • The issue is 100% with the trailing space. I have added an answer to explain to the OP why it occurs and why its the problem. – Chris Doyle Jan 08 '20 at 09:39
  • i had update the code please look into – hani Jan 08 '20 at 12:42
  • I have voted to close the question as your question gives no clear problem statememtn with minimable example to reproduce your error you dont explain why things are wrong when in actual fact according to binary addition rules they are actually correct. – Chris Doyle Jan 08 '20 at 14:21

5 Answers5

1

space not effect, i remove the space and the answer is same wrong

I tried your script and found out you have an extra space on the right side of your value variable. If you remove it, it should work (returns 010). I would recommend to trim your input values before proceeding with the algorithm.

value = value.strip()

If you just interested in the result but not in implementation (May be you are trying to learn something new or it is an assignment), you can first convert the binary numbers to int and add them and again convert back to binary string.

See this code:

value = '001 '
demo = '001'
def add_binary_nums(x,y):
        x_int = int(x, 2)
        y_int = int(y, 2)
        result = x_int + y_int
        return '{0:08b}'.format(result)

print(add_binary_nums(value, demo))

Output:

00000010

To understand '{0:08b}'.format(result), visit this link.

EDIT:

thx, for sure i care about the implementation, its not assignemt or homework to convert numbers into binary, and the code above its peace of my program, im passing many variables have binary number i give u one example , when i pass variable from other python code, assume , n="011000100110111101100010" and m="0001", when i run the code , its shows wrong answer!, remember i'm pass variable and i got result 011000100110111101100110 !

Try the code below. I am getting the right results with python3.

value = '011000100110111101100010'
demo = '0001'
def add_binary_nums(x,y):
        x=x.strip()
        y=y.strip()
        max_len = max(len(x), len(y))
        print("Max: %d X: %s Y %s" %(max_len, x, y))
        x = x.zfill(max_len)
        y = y.zfill(max_len)

        result = ''
        carry = 0

        print("X: %s Y: %s" % (x, y))

        for i in range(max_len-1, -1, -1):
            print(i)
            r = carry
            r += 1 if x[i] == '1' else 0
            r += 1 if y[i] == '1' else 0
            result = ('1' if r % 2 == 1 else '0') + result
            carry = 0 if r < 2 else 1

        if carry !=0 : result = '1' + result

        return result.zfill(max_len)
demoo = (add_binary_nums(demo, value))
print(demoo)
abhiarora
  • 9,743
  • 5
  • 32
  • 57
  • thx, for sure i care about the implementation, its not assignemt or homework to convert numbers into binary, and the code above its peace of my program, im passing many variables have binary number i give u one example , when i pass variable from other python code, assume , n="011000100110111101100010" and m="0001", when i run the code , its shows wrong answer!, remember i'm pass variable and i got result 011000100110111101100110 ! – hani Jan 08 '20 at 12:29
  • I tried your code again and getting the right results. Try my code in the edited section. – abhiarora Jan 08 '20 at 12:45
  • your code is right sir, but when i pass another varible with value assume s='01100010011011110110001001000000011001110110110101100001011010010110110000101110011000110110111101101101' and s2='0110111001100101011101110010000001011001011011110111001001101011' and s3='00101011001100010011001100110101001100010011011100110111001110010011100000110110' the result got wrong – hani Jan 08 '20 at 13:02
  • Well I tried again with the above values and it is working. Can you add `print` calls and print argument values and their length and post it here? – abhiarora Jan 08 '20 at 16:04
  • 1
    I am not sure why I have been downvoted. If someone is lacking in my answer, please do comment as well! – abhiarora Jan 09 '20 at 05:58
  • the value of the argument is s=bob@gmail.com , s2=new york, s3=+135177986 , the length for each s=104, s2=64,s3=80 , you can check the value after addition and subtraction u will get not same value of original – hani Jan 09 '20 at 06:30
  • @bhiarora, your answer is accepted but but not for all values ,thank you – hani Jan 09 '20 at 06:31
1

The problem only exists with the trailing space. When running the code with trailing space it produces the output 0011, when running the code without the trailing space produces the output 010

The reason this occurs is due to the space and how you use zfill. If we look at the data when there is a trailing space on one of them.

if we assume x="001" and y='001 ' then max_len will be set as 4 since y has 4 chars in it. you then do zfill on x and zfill on y. this will pad x with an extra leading 0 to make it 4 chars. It will have no effect on y since its already 4 chars. So you will end up with

x="0001"
y="001 "

As you can see these are now not in the same representation. So when you start to do your calculations your first iteration on index 3 will be comparing the "1" from x and the space char from y. You code says if its not a 1 then its a 0. since space isnt a 1 then you default it to a 0.

So your essentially treating it like

x="0001"
y="0010"

and the result of that would indeed correctly be "0011"

So the issue is 100% with your space in the string. I would suggest either validate your input to the function to be sure it contains only 1s or 0s if it doesnt raise a ValueError. Or at a minimum call strip method of string to remove any leading or trailing spaces from the string.

Chris Doyle
  • 10,703
  • 2
  • 23
  • 42
  • you are right if i'm initialize the value with the variable, but still when i'm passing variable from other python code, its shows wrong answer, try define your variable in other code and import into the program, the result will be wrong – hani Jan 08 '20 at 12:31
  • Then what you are passing is not what you think. Python is not a complicated language. your code works as expected, it doesnt care where the parameters passed to the function come from. they could come from an enviroment variable, from user input, from a variable from a value of a dict key, it doesnt care. you are clearly not telling the full story here. The only way to get any real help here is to post the real problem your facing, as the one you posted clearly isnt what your having an issue with – Chris Doyle Jan 08 '20 at 12:49
  • sir, i have update the code , and its the real problem as its , nothing else, im adding binary number to other binary number, the results of binary number is different ,even if i pass any other parameter its same, i have attach example, u can check the update code – hani Jan 08 '20 at 14:11
0

Look at how you initialized your variables (empty space, quotes). Seems off to me for a binary representation...

value = '001 '  
demo = "001"
SnowGroomer
  • 695
  • 5
  • 14
0

Just use python binary literals: How do you express binary literals in Python?

Rewrite print(add_binary_nums(value, demo)) as print(bin(int(value, 2), int(demo, 2)))

R Harrington
  • 253
  • 2
  • 10
0

running your code leaves me with the result 0011 not as you mentioned 001001. Leaving out the space in the first "value" variable leaves me with the result 010.

Hope this helps!

Edit: I also would suggest to just add the numbers in int-mode and then convert the int back to binary if you insist in having the space and the input as you have.

Pyretu
  • 23
  • 4
  • try import the value as variable from other python code, and the answer will be same wrong, because i'm import variable from other python code – hani Jan 08 '20 at 12:32
  • i had update the code, plz look into – hani Jan 08 '20 at 12:42