简体   繁体   English

如何检查给定的输入是否为二进制数?

[英]How to check the given input is binary number or not?

I need to write a logic to print message like it's a binary or it's not a binary我需要编写一个逻辑来打印消息,就像it's a binaryit's not a binary一样

Input 1: 100001输入 1: 100001

Input 2: 001输入 2: 001

Input 3: 101输入 3: 101

I have written below code:我写了下面的代码:

n=str(input('enter the number'))

if len(n) == 8:
   print("it's a binary")
else:
   print("it's not a binary")

Seems like this is not a right approach any other way to identify似乎这不是任何其他识别方法的正确方法

Output 1: It's a binary Output 1:这是一个二进制

Output 2: It's a binary Output 2:这是一个二进制

Output 3: It's a binary Output 3:这是一个二进制

101, 001 -> if padded with zero from left then it becomes 8 digit binary number 101, 001 -> 如果从左开始用零补齐则变成8位二进制数

Invalid binary numbers: 254, 66, 72, 1056无效的二进制数: 254, 66, 72, 1056

Binary should contain only 1 and 0二进制应该只包含10

Try using sets, it should make it easy.尝试使用集合,它应该很容易。 A set will take the unique items of your string, thus for a binary number you can match for 0 and 1 as strings in a set.集合将采用字符串的唯一项,因此对于二进制数,您可以将 0 和 1 匹配为集合中的字符串。

The "pipe" or the "or" operation will join the sets and if there's anything more than the set of zeroes and ones, it'll fail. “管道”或“或”操作将加入集合,如果除了零和一的集合之外还有任何其他内容,它将失败。

Notice it'll be true on an empty input, for that check for If text and... .请注意,在空输入上它会为真,用于检查If text and... ( (set()|{'0', '1'}) == {'0', '1'} ] ( (set()|{'0', '1'}) == {'0', '1'} ]

Alternatively set.issubset() should be a replacement for the == operator, if that suits you better.或者set.issubset()应该替代==运算符,如果它更适合您的话。

text = input()
if (set(text) | {'0', '1'}) == {'0', '1'}:
    print("binary")

You can iterate over the int as a str and check if it only contains '0' and '1' :您可以将int作为str进行迭代并检查它是否仅包含'0''1'

n = input()
if not n: # So n is different from '' (empty string)
    print('Not binary')
    return
for i in n:
    if (i not in ['0', '1']):
        print('Not binary')
        return
print('Binary')

Your previous check strategy won't work at all, according to your code:根据您的代码,您以前的检查策略根本不起作用:

  • 01234567 -> It's a binary 01234567 -> 这是一个二进制文件
  • 0101 -> It's not a binary 0101 -> 它不是二进制的

To check this you can anyway use the re Python library (re stands for regex , reg ular ex pression):要检查这一点,您无论如何都可以使用re Python库(re 代表regex ,正则表达式

import re
pattern = re.compile('^[0-1]{8}$') # A string made out of 0 and 1 and of lenght 8
if pattern.match(input()):
    print('Binary of lenght 8')
else:
    print('Not a binary of lenght 8')

If you don't care about lenght, you can use set s, a Python's iterable class that doesn't admit duplicate elements in it:如果你不关心长度,你可以使用set s,一个 Python 的iterable class ,它不允许重复元素:

>>> set(['1', '1', '0'])
{'1', '0'}
>>> set('01011010101010')
{'0', '1'}

Then you can write something like this:然后你可以写这样的东西:

if set(input()) in [{'0', '1'}, {'0'}, {'1'}]:
    print('Binary')

As @azro suggested, a better syntax is using set instance method issubset , like this:正如@azro 建议的那样,更好的语法是使用set实例方法issubset ,如下所示:

if set(input()).issubset({'0'}, {'1'}):
    print('binary')

One approach can be if the string contains either 0 or 1 only then we can conclude it is a binary otherwise not.一种方法是,如果字符串仅包含01 ,那么我们可以断定它是二进制文件,否则不是。

given_string = input('enter the number')
# set function convert string into set of characters
p = set(given_string)
 
# declare set of '0', '1'
s = {'0', '1'}
 
# check set p is same as set s or set p contains only '0'
# or set p contains only '1'or not, if any one condition
# is true then string is accepted otherwise not accepted
if s == p or p == {'0'} or p == {'1'}:
        print("Yes")
else :
        print("No")

Alternatively you can try the issubset method of set using the following approach:或者,您可以使用以下方法尝试 set 的issubset方法:

given_string = input('enter the number')
x = {"0", "1"}
y = set(given_string)
if y.issubset(x): 
      print("Binary")
else:
      print("Not Binary")

Try this:尝试这个:

n = input('enter the number: ') # `n` is already of type `str`
if all(c in '01' for c in n):
    print("it's a binary")
else:
    print("it's not a binary")

In case to check for an 8 bit binary如果要检查 8 位二进制文件

import re
pattern = re.compile("^([0-1]{8})$")
strings=[
    "00000001",
    "12345678",
    "101",
]
for string in strings:
    if pattern.match(string):
        print(f"{string} is binary")
    else:
        print(f"{string} is not binary")

Output Output

00000001 is binary
12345678 is not binary
101 is not binary   

In case the binary number can contain any number of zeros and ones or less use如果二进制数可以包含任意数量的零和一或更少,请使用

"^([0-1]+)$"

May be this could help you to get desired output可能这可以帮助您获得所需的 output

Code:代码:

import re
a=190
check_values_exist = re.findall('[2-9]+', str(a))

if len(check_values_exist) == 0:
  print("It's binary")
else:
  print("It's not a binary")

Output: Output:

It's not a binary

I would do this as follows:我会这样做:

def is_binary(s):
  # bool(s) guards against the case of s = ""
  return bool(s) and all(c in "01" for c in s)

def is_binary2(s):
  try:
    # check if the builtin int type can parse a binary string
    res = int(s, base=2)
    return True
  except:
    return False

The first approach checks if all digits are 0 or 1, and takes care of the empty string case.第一种方法检查所有数字是 0 还是 1,并处理空字符串的情况。 The second approach delegates all of the works to the standard library.第二种方法将所有工作委托给标准库。

  1. Input return a string so the str() is useless输入返回一个字符串,所以 str() 没用
  2. Your outputs are wrong.你的输出是错误的。
  3. Your code return if a str could be a byte.如果 str 可能是一个字节,您的代码将返回。
  4. Here is a code to know if a string is a byte:这是一个知道字符串是否为字节的代码:
def is_binary(n:str) -> bool :
    return len(n) = [for i in n if i == "0" or i == "1"]

def is_byte(n:str) -> bool :
    return is_binary(n) and len(n) = 8

print(is_byte(10010110))
-> True
print(is_byte(100a01c0))
-> False
print(is_byte(101))
-> False

You can also convert str to set to know if it is a binary number;)您还可以将 str 转换为 set 以知道它是否是二进制数;)

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

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