Python字典|检查两个数字的二进制表示形式是否为字谜

给定两个数字,你需要检查它们是否是二进制表示中彼此的字谜。

null

例如:

Input : a = 8, b = 4 
Output : Yes
Binary representations of both
numbers have same 0s and 1s.

Input : a = 4, b = 5
Output : No

我们有解决这个问题的现有方案,请参考 检查两个数字的二进制表示是否为字谜 链接我们可以使用python快速解决这个问题 计数器(可调) 方法和 字典比较 .方法很简单,

  1. 使用以下命令将这两个数字转换为二进制 bin() 作用
  2. 由于两个数字的二进制表示形式可能在长度上有所不同,所以我们将在较短字符串的开头添加零,以使两个字符串的长度相等。即。;附加零=abs(len(bin1)-len(bin2))。
  3. 使用将bin函数返回的包含0和1的输出字符串转换为字典 计数器() 函数,具有0键和1键,并将其计为值。比较两个字典,如果两个字典中的0和1的值相等,则两个数字的二进制表示是字谜,否则不是。

# function to Check if binary representations
# of two numbers are anagram
from collections import Counter
def checkAnagram(num1,num2):
# convert numbers into in binary
# and remove first two characters of
# output string because bin function
# '0b' as prefix in output string
bin1 = bin (num1)[ 2 :]
bin2 = bin (num2)[ 2 :]
# append zeros in shorter string
zeros = abs ( len (bin1) - len (bin2))
if ( len (bin1)> len (bin2)):
bin2 = zeros * '0' + bin2
else :
bin1 = zeros * '0' + bin1
# convert binary representations
# into dictionary
dict1 = Counter(bin1)
dict2 = Counter(bin2)
# compare both dictionaries
if dict1 = = dict2:
print ( 'Yes' )
else :
print ( 'No' )
# Driver program
if __name__ = = "__main__" :
num1 = 8
num2 = 4
checkAnagram(num1,num2)


输出:

Yes
© 版权声明
THE END
喜欢就支持一下吧
点赞10 分享