简体   繁体   English

如何比较python(和,或,异或)中的两个数字?

[英]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:我是编程新手,我正在尝试为以下练习找到 python 解决方案: 在此处输入图片说明

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.我需要比较所附图像中 3 个案例的 2 个数字的二进制形式(AND、OR、XOR)。Bellow 是我的代码,但我不知道如何使其适用于所有 3 个案例。 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.问题是第一个循环修改了输入变量ab并将它们保留为零。 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.我写了一个很长的答案,因为我希望在第一次学习 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.请注意,您的代码的“问题”仅仅是使用位移来修改 a 和 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.这根本没有任何作用,因为sep仅在有多个条目时才应用。 Compare this:比较一下:

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

Can you see what sep does?你能看到sep做了什么吗? The reason this line does what you think it does is that the default for end is also \\n .此行执行您认为的操作的原因是end的默认值也是\\n To print a blank line you can use print(end="\\n") , which is equivalent to print() , so the latter form is preferred.要打印空行,您可以使用print(end="\\n") ,它等效于print() ,因此首选后一种形式。

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 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.您已经对第一个问题有了很好的解决方案:使用bin()获取字符串并对其进行迭代。 But you have a few paradigms in play, including using << to shift, which as @MarkRansom notes is modifying your integers.但是你有一些范式在起作用,包括使用<<来转换,正如@MarkRansom 指出的那样,它正在修改你的整数。 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 .以“and”的情况为例,因为它是最简单的(我将其他比较留给您),因此测试显然是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:但是记住1在 python 中是真的,更好的是:

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

And if we want 1 and 0:如果我们想要 1 和 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). listcomp 可能是“手动”解决这些问题的最正常方法,我在这里遵循的步骤可以用于其他情况(或 xor、nand 等)。

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如果你想深入了解 Python 中的位运算符,我会在下面留下一个链接

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

Hope the code serves the purpose希望代码可以达到目的

Regards问候

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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