Checking is a string is binary - python

I am trying to solve a python programming challenge that requires a program for checking if a string is binary. If the string is binary, it should return "true". Otherwise, it should return "false".
When I ran the code, it iterates through the string and prints either "true" or "false" depending on whether the value in the string is "0" and "1" or not. Even though I have tried a couple of methods I keep ending up with a vertical display of the boolean values.
binary = {'0', '1'}
def is_binary(string):
for i in str(string):
if i in binary:
print('true')
else:
print('false')
break
is_binary('101010')
is_binary('101210')
How can I modify the code to be able to print a single "true" statement when the string is binary and a single "false" statement when the string is not binary regardless of the length of the string?

You do something like this:
def is_binary(str):
is_binary = True
try:
int(str, 2)
except ValueError:
is_binary = False
return is_binary
is_binary('0101010101010') # returns True
is_binary('24340101041042101010') # returns False
I have use int to convert to binary, Please refer here to learn

Try the below code:
def is_binary(bin_str):
if (set(bin_str) - set(['1','0'])):
return False
else:
return True
bin_str = "0110011"
print is_binary(bin_str)
bin_str = "011020"
print is_binary(bin_str)
Output:
True
False
Solution using OP's logic:
binary = {'0', '1'}
def is_binary(string):
for i in str(string):
if i in binary:
continue
else:
return False
return True
print is_binary('101010')
print is_binary('101210')

The problem in your code is that you are printing if every character was in binary set which is NOT what you want. You want to print true only if all the characters were in binary. So, you only need to print('true') at the end of the for loop.
So, This should do it:
binary = {'0', '1'}
def is_binary(string):
for i in str(string):
if i not in binary:
print('false')
return
print('true')
is_binary('101010')
is_binary('101210')

Short way
I stumble here and thought about this:
# Declare one true and one false vars
bb = '010010111010010001011100'
bb2 = '010010111010010001O11100' # there's a letter O here
bin_set = set('0','1') # A set with char '0' and char '1'
I also could have written bin_set = {'0','1'}
Then (I was in ipython 3):
In : set(bb) == bin_set
Out: True
In : set(bb2) == bin_set
Out: False
If a string is only composed with 0 and 1 then its set() will be equal to {'0','1'} (set representation in python)
hth

Related

how can i use a function to identify if zero is the first number in an alphanumeric string?

I'm trying to create a function that will identify if 0 is the first number in an alphanumeric sequence; for example, the function should evaluate to True if given the string "J02". I came up with a for loop that would work for inputs that are alphanumeric but not strictly alpha inputs.
x = "J02"
def not_starting_zero(m):
zero_string = []
for char in m:
if char.isdigit() == True:
zero_string.append(char)
if m[len(m)-1] == char:
if zero_string[0] == "0":
return False
else:
return True
not_starting_zero(x)
I tried using an else statement that aligned with the indentation of the if char.isdigit() == True: ; but that would make the return of the function true if the first index of the string is a letter.
You could use a regular expression to find the first digit:
import re
def not_starting_zero(m):
first_digit = re.search(r"([0-9])", m)
if first_digit:
return first_digit.group(0) == "0"
else:
return False
Alternatively, you could use your looping version - I think you can just stop after you encounter the first digit:
x = "J02"
def not_starting_zero(m):
for char in m:
if char.isdigit() == True:
if char == "0":
return True
# otherwise, return False
return False
# if we get here, there weren't any numbers
return False
not_starting_zero(x)
I suppose you could use regex and extract the numeric digits into a list. Something like this -
import re
def not_starting_zero(m):
numbers = re.findall('[0-9]', m)
if numbers[0] == '0':
return false
else
return true
I'm assuming you mean the first digit you find is 0 (because otherwise it should return False for "J02" because 02 is the first number)
x = "J02"
def not_starting_zero(m):
for char in m:
if char.isdigit() == True:
if char == "0":
return True
else:
return False
return False
not_starting_zero(x)
This works because once return is executed in a function the rest of the function is not executed. Hope this clears up your doubt.
You don't need to make an array of the digits because you only need to check the first digit in the string; if its a 0 then return True else return False.
Below code can find if 0 is the first number in alphanumeric string.
import regex as re
x = "J02"
True if re.findall('[0-9]', x)[0] == '0' else False
Output:
True
Take note on type safety, how expressive the code is, and how it instills referential transparency for code correctness (accuracy). All those loops cause too many mutations, and mutations cause errors (bugs). See here for referential transparency.
import re
str1 = 'jdh487y3hef8ty483rhfeih89t4389jf0dwiefh38uth'
str2 = '0dh487y3hef8ty483rhfeih89t4389jfdwiefh38uth'
# check if a given char is first in letter in string
def check_for_char(alpha_num:str, _char) -> bool:
if re.search('0', alpha_num).span(0)[0] == _char:
return True
else:
return False
is_false = check_for_char(
alpha_num=str1,
_char=0
)
is_true = check_for_char(
alpha_num=str2,
_char=0
)
print(is_false) # False
print(is_true) # True
# search if a given char exists at all within the alphanum str
print(str1[re.search('0', str1).span(0)[0]]) # 0

Trying to make a python recursive function that checks if a character is in the given string however i have failed to

def q5(s,c):
if s == "":
return s
elif c != s[0]:
return False
else:
return True
return q5(s[1:], c)
Takes an string s and a single-character string c as inputs and uses recursion to determine if s contains the character c, returning True if it does and False if it does not.
and I'm using recursion to process s one character at a time and determine if c is contained in s.
Args:
s (str): input string
, c (str): single character
Im having issues doing this and when I do q5("HI", "H") it returns true because "H" is in "HI" however when I do q5("HI", "I") it returns false even though "I" is also in the string "HI".
The issue is you're returning False if the first character doesn't match. You need to return True if it does match and then recurse if it doesn't; eventually you return False if you get to the end of the string.
def q5(s,c):
if s == "":
return False
elif c == s[0]:
return True
else:
return q5(s[1:], c)
You basically want to know if the first character of the string equals the search character or that character occurs in the rest of the string.
You can translate that idea directly and very succinctly with:
def q5(s,c):
if s == "":
return False
return s[0] == c or q5(s[1:], c)
q5("HI", "I")
# True
q5("HI", "H")
# True
q5("HI", "f")
# False
There is a simpler way to achieve this without needing recursion, you can check for the letter like so:
def q5(s,c):
if c in s:
return True
else:
return False

Python: Verify Credit Card digits

I need to implement a function called “verify” that takes a single parameter
called “number” and then checks the following rules:
The first digit must be a 4.
The fourth digit must be one greater than the fifth digit; keep in mind that these
are separated by a dash since the format is ####-####-####.
The sum of all digits must be evenly divisible by 4.
If you treat the first two digits as a two-digit number, and the seventh and eighth
digits as a two-digit number, their sum must be 100
This is what I have come up with so far:
def verify(number): # do not change this line!
list_number=list(number.split(''))
Check=false
# write your code here so that it verifies the card number
if list_number[0]==4:
if list_number[3]==list_number[5]+1:
if list_number.sum() % 4==0:
if int(str(list_number[0])+str(list_number[1]))+int(str(list_number[7])+str(list_number[8])) ==100:
Check = true
else:
check = false
input = "4094-3460-2754" # change this as you test your function
output = verify(input) # invoke the method using a test input
print(output) # prints the output
this is what you need. each if statement in the function corresponds to condition that you have specified.
def verify(number): # do not change this line!
number_string = number.replace("-", "")
list_number = [int(n) for n in number_string]
if not list_number[0] == 4:
return False
if not list_number[3] - list_number[4] == 1:
return False
if not sum(list_number) % 4 == 0:
return False
if not int(number_string[0:2]) + int(number_string[6:8]) == 100:
return False
return True
input = "4094-3460-2754"
output = verify(input)
print(output)
# True
It seems like there are a few fundamental errors in your code. I will list them down for you:
Boolean values start with a capital
there are no indentations after your if and else statements
Your output will always print none as your function does not return anything.
def verify(number):
list_number=list(number)
if list_number[0]==4 and list_number[3]==list_number[5]+1 and list_number.sum() % 4==0 and int(str(list_number[0])+str(list_number[1]))+int(str(list_number[7])+str(list_number[8])) ==100:
return True
else:
return False
input = "4094-3460-2754"
output = verify(input)
print(output)```
Your code is way to poorly written
list_number = "4094-3460-2754"
list_number = list_number.replace('-','')
if list_number[0]=='4' and int(list_number[3])==int(list_number[5])+1 and list_number.sum() % 4==0 and int(list_number[0])+int(list_number[1])==int(list_number[7])+int(list_number[8]):
check = True
else:
check = False

verify the first digit of input is a 4

I have been given a string of digits and I must create a function that verifies if the first number in the string is equal to 4.
def verify(number) :
int (input[0],10)
for number in input:
if input [0] == 4:
return True
elif input [0] != 4:
return False
input = "5000-0000-0000"
The result should be false but should print true if I change the input to 4000-0000-0000
You should compare to the string "4". Also, comparison returns a Boolean anyway, so you can get rid of the if statements:
def verify(number):
if not number:
return False
return number[0] == "4"
Note that you should check the length of the string with not number to avoid errors when an empty string is passed. Another option is startswith:
def verify(number):
return number.startswith("4")
In this case, a check is not needed. However, this approach tends to be a bit slower because startswith is a more complex operation than a simple comparison.
Here, this should work:
def verify(number):
number = str(number)
if number.startswith("4"):
return True
else:
return False
It takes the var number, converts it to a string, checks if it starts with "4", and if it does, it returns true, otherwise it returns false.
def verify(number):
number = str(number) #convert number to string
if number.startswith("4"): #check if it starts with 4
return True # return True if it does
else:
return False #otherwise return false
EDIT:
As #melpomene suggested, this code can be further simplified:
def verify(number):
return str(number).startswith("4")
If you need to verify the exact pattern but starting with 4 then something like this:
def verify(s) :
from re import match
if match('^4[0-9]{3}\-[0-9]{4}\-[0-9]{4}$',s): return True
return False
print(verify("5000-0000-0000"))
print(verify("4000-0000-0000"))
or as was pointed out in the comments:
if match('^4\d{3}\-\d{4}\-\d{4}$',s): return True
If you want to verify just one digit, write the following function:
def verify_number(text):
has_4 = (text[0] == 4)
if has_4:
return True
return False
>>> verify_number("5000-0000-0000")
False
>>> verify_number("4000-0000-0000")
True
If you want to create a more generalizing function, which identifies if the first character is equal to any number (0-9), just do:
def verify_number(text, number):
has_n = (text[0] == number)
if has_n:
return True
return False
>>> verify_number("5000-0000-0000", "5")
True
>>> verify_number("4000-0000-0000", "4")
True

Python, checking if string consists only of 1's and 0's

I'm trying to write a function that checks if given string is binary or not. I'm using a while loop to browse characters in string one by one. If all of them are 0's or 1's it's going to return True, if anything is not - break the loop and return False.
I've just written this tiny part of code, but it doesn't run. Why?
def fnIsBin(string):
count = 0
while count < len(string):
character = string[count]
if character == '0' or character == '1':
print (count, character[count], "OK")
count = count+1
continue
else:
print (count, character[count], "ERROR")
return False
break
EDIT:
I also tried using 'set' to elude iterating with loop, but i don't quite get how does "set(string)" work. I got error that i cant consider it as a list. So how can I compare elements to 0 & 1?
def fnIsBin(string):
charactersList = set(string)
if len(charactersList) > 2:
return False
else:
if (charactersList[0] == '0' or charactersList[0] == '1') and (charactersList[1] == '0' or charactersList[1] == '1'): #there i made error, how to deal with it?
return True
else:
return False
Your function fails because you never actually return True. That means if the string is actually binary, you'd return None which Python would consider as False in any boolean check.
Simply add return True at the end of the function.
As #Barmar mentioned in the comment, you also print the value of character[count] instead of string[count] which would cause IndexError.
An easier way to check if the string is binary would be:
test_string = '010101'
all_binary = all(c in '01' for c in test_string)
There are many ways to do this:
Set:
fnInBin(s):
return set(s).issubset({'0', '1'}) and bool(s)
Regular expression:
fnInBin(s):
return bool(re.fullmatch('[01]+', s))
Integer conversion:
fnIsBin(s):
try:
int(s, 2)
return True
except ValueError:
return False
The last one will strip whitespace from the input, though.
fnIsBin('\n 1 ') == True
You can use the int object and give it a base. It will fail if the object passed doesn't consist of a binary representation. Recall that a binary string is base 2.
def fnIsBin(string):
try:
binary_repr = int(string, 2)
except ValueError as err
print("error: {0}".format(err))
return False
return True
You're printing OK for each character that's 0 or 1, even though there may be a later character that isn't. You need to wait until the end of the loop to know that it's really OK.
def fnIsBin(string):
for character in string:
if character != '0' and character != '1':
print (character, "ERROR")
return False
print "OK"
return True
There's no need for break after return False -- returning from the function automatically breaks out of the loop.
Here's one of the ways you could rewrite your function and maintain a similar structure (looping through each character):
def fnIsBin(string):
for character in string:
if not character in '01':
return False
return True
You could also do it using regular expressions:
import re
def fnIsBin(string):
return re.match(r'^[10]+$', '01') is not None
My two cents (A short way):
test_string = '010101'
result = set(test_string) <= {'0','1'}
print(result)
Using set(test_string) converts the string into list of characters,
{0,1,0,1,0,1}
Using <= operator checks whether the set on the left-side is a proper subset of the set on the right-hand side
Ultimately checking whether there are only 0 and 1 are in the string or not in an in-direct and mathematical way.
Adding a XOR solution to the mix:
bin_string = '010101'
for j in range(0, len(bin_string)):
if int(bin_string[j]) != 0 ^ int(bin_string[j]) != 1:
break

Categories

Resources