简体   繁体   中英

How do I compare two numbers in python(and, or, xor)?

I am new to programming and I am trying to find the python solution to the below exercise: 在此处输入图片说明

I need to compare the binary form of 2 numbers for the 3 cases from the attached image(AND, OR, XOR).Bellow is my code but I dont know how to make it work for all 3 cases. Thank you!

a,b = int(input("Please enter the first number: ")),int(input("Please enter the second number: ")) 
m = ""
n = ""
p = ""

print(sep="\n") 


print(bin(a),bin(b),sep="\n")
print(sep="\n") 

length = max([len(bin(a)), len(bin(b))])-2 

# AND 
for i in range(length):
    if bin(a)[-1]== "1" and bin(b)[-1]== "1":
        m+= "1"
    else:
        m+= "0"        
    a = a >> 1
    b = b >> 1 
    
    
print ("0b" + m[::-1],"| AND") 

#OR
for i in range(length):
    if bin(a)[-1]== "1" or bin(b)[-1]== "1":
        n+= "1"
    else:
        n+= "0"        
    a = a >> 1
    b = b >> 1 
   
print ("0b" + n[::-1],"| OR")  
 
#XOR
for i in range(length):
    if bin(a)[-1] != bin(b)[-1] :
        p+= "1"
    else:
        p+= "0"      
    a = a >> 1
    b = b >> 1 
print ("0b" + p[::-1],"| XOR")

The problem is that the first loop modifies your input variables a and b and leaves them at zero. That means the second and third loops have nothing to work with.

The easiest way to fix this is to put each loop in a separate function, the function can't modify the values that are passed in so they'll be automatically restored.

I've written out a long answer because I wish someone had when I was first learning python. Note that I very deliberately walk through all the steps and I don't present final code for everything. Sorry if it goes too slowly: I was trying to be clear, not patronising. Note the 'problem' with your code is merely the use of bitshifts to modify a and b.

There are quite a few 'interesting' ways of doing things in this code which it might be worth considering the 'standard' solutions to:

Printing blank lines

print(sep="\n")

This does nothing at all, because sep is only applied when there are multiple entries. Compare this:

print("hello", "world", sep="\n")

Can you see what sep does? The reason this line does what you think it does is that the default for end is also \\n . To print a blank line you can use print(end="\\n") , which is equivalent to print() , so the latter form is preferred.

Bitwise comparison

The easiest way to compare two numbers on the bit level is to do it with bitwise operations:

a = 0b11110000
b = 0b10101010
a & b # and

For the other bitwise operators, see:

https://wiki.python.org/moin/BitwiseOperators

Manual bitwise

The manual bitwise problem can be thought of as 'iterate the numbers by digit and do something on the digit'. You already have a good solution to the first problem: use bin() to get a string and iterate that. But you have a few paradigms in play, including using << to shift, which as @MarkRansom notes is modifying your integers. It would be more 'standard' to adopt a single iterating paradigm. Naively:

a = bin(0b11110000)
b = bin(0b10101010)

for i in range(len(a):
   a_digit = int(a[i])
   b_digit = int(b[i])
   # comparison here

but more idiomatically:

for a_digit, b_digit in zip(a, b):
    comparison(int(a_digit), int(b_digit))

Taking the 'and' case, since it's the easiest (I leave the other comparisons to you), the test is clearly a_digit == 1 and b_digit == 1 . So we would write:

res = []
for a_digit, b_digit in zip(a,b):
    res.append(int(a_digit) == 1 and int(b_digit == 1))
# res = [True, True, True, True, False, False, False, False]

but remembering that 1 is truthy in python, better would be:

res.append(int(a_digit) and int(b_digit))

And if we want 1 and 0:

res.append(1 if int(a_digit) and int(b_digit) else 0)

At which point we are ready to wrap it all up into a list comprehension:

res = [1 if int(a_digit) and int(b_digit) else 0 for a_digit, b_digit in zip(a,b)]

This paradigm is really worth learning . A listcomp is probably the most normal way to solve each of these problems 'manually', and the steps I've followed here can be worked through for the other cases (or, xor, nand, etc).

def decimalToBinary(n):
    return bin(n).replace("0b", "")

## Uncomment the below two lines of code, if you are inputting the numbers in decimal format
# bin_a = str(decimalToBinary(int(input("Enter first number: "))))
# bin_b = str(decimalToBinary(int(input("Enter second number: "))))

## Uncomment the below two lines of code, if you are inputting the numbers in binary format
# bin_a = str(int(input("Enter first number: ")))
# bin_b = str(int(input("Enter second number: ")))

len_bin_a = len(bin_a)
len_bin_b = len(bin_b)

if len_bin_a > len_bin_b:
    bin_b = "0" * (len_bin_a - len_bin_b) + bin_b

elif len_bin_a < len_bin_b:
    bin_a = "0" * (len_bin_b - len_bin_a) + bin_a

or_result = "".join([str(int(bin_a[i]) | int(bin_b[i])) for i in range(len(bin_a))])
and_result = "".join([str(int(bin_a[i]) & int(bin_b[i])) for i in range(len(bin_a))])
xor_result = "".join([str(int(bin_a[i]) ^ int(bin_b[i])) for i in range(len(bin_a))])

print(or_result + "\tOR")
print(and_result + "\tAND")
print(xor_result + "\tXOR")

I will leave a link below if you wanna wander deep into Bitwise Operators in Python

https://www.geeksforgeeks.org/python-bitwise-operators/

Hope the code serves the purpose

Regards

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM