I need some advice for this challenge. The requirements are to see if the input is valid (i.e. only 0s and 1s, no spaces, and no letters) and accepted (contains two 1s). Then, if the input is valid and accepted, translate the binary into decimal. Any help would be appreciated!
#Examples of invalid binary numbers: abc 10102011 10101FF
#0000 1111 (note:contains a space)
#Examples of valid, rejected binary numbers: 00000000 1111 01110000001
#Examples of valid, accepted binary numbers: 1000001 11000000 1111
binary = str(input("Enter a binary number: "))
binary_list = list(binary)
valid = True
accepted = True
convert = ""
var = binary_list.count('1')
for character in binary_list:
if (character != '1') and (character != '0'):
valid = False
for character in binary_list:
if (var != 2):
accepted = False
if (valid == True and accepted == True):
print("Input", binary ,"is valid and accepted")
convert = int(binary, 2)
print ("The number is ", convert)
elif (valid == False):
print ("Input was invalid")
elif (valid == True and accepted == False):
print ("Input was rejected")
You can use sets to check if the input only contains 0's and 1's.
>>> set("1101101000100001001010101")
{'0', '1'}
No matter what the result is, it should only contain some subset of {'0', '1'}. (There's a chance it won't have one or the other.) We can use the set.issubset() method to check this. (Note the 2 in the second example.)
>>> set("11010001").issubset(('0', '1'))
True
>>> set("11010201").issubset(('0', '1'))
False
Finally, like you found, you can use str.count() to figure out if there are exactly two 1's.
>>> "1001".count('1')
2
Here's the entire code block.
if not set(binary).issubset(('0', '1')):
print("Input was invalid binary.")
elif binary.count('1') != 2:
print("Input was rejected.")
else:
print("Input", binary, "was valid and accepted!")
Note the reordering of the statements; rather than first checking for entire validity and otherwise trying to determine points of failure, we can check for individual fail cases with if/elifs, and then place the success case afterwards in the else block.
Edit: If you would like to keep using the strategy that you outlined in your code example, you can add break in the if block of the first for loop, to stop searching after a fail case was found. The second for loop is also unnecessary, as you are not using the character at all, and it can be removed (keeping the if block "outside").
Also, note that the conversion from binary to binary_list is unnecessary, as strings may be iterated over and have the .count() method, as well.
for character in binary:
if character != '1' and character != '0':
valid = False
break
if var != 2:
accepted = False
Related
I can accept user's input in two formats:
123
123,234,6028
I need to write a function/a few lines of code that check whether the input follows the correct format.
The rules:
If a single number input, then it should be just a number between 1 and 5 digits long
If more then one number, then it should be comma-separated values, but without spaces and letters and no comma/period/letter allowed after the last number.
The function just checks if formatting correct, else it prints Incorrect formatting, try entering again.
I would assume I would need to use re module.
Thanks in advance
You can use a simple regex:
import re
validate = re.compile('\d{1,5}(?:,\d{1,5})*')
validate.fullmatch('123') # valid
validate.fullmatch('123,456,789') # valid
validate.fullmatch('1234567') # invalid
Use in a test:
if validate.fullmatch(your_string):
# do stuff
else:
print('Incorrect formatting, try entering again')
Another option is:
def validString(string):
listofints = [v.isdigit() for v in string.split(",") if 0 < len(v) < 6]
if not len(listofints) or not all(listofints):
print("Incorrect formatting, try entering again.")
The following code should leave the Boolean variable valid as True if the entered ibnput complies with your rules and False otherwise:
n = input("Your input: ")
valid = True
try:
if int(n) > 9999:
valid = False
except:
for character in n:
if not character in "0123456789,":
valid = False
if n[-1] == ",":
valid = False
I'm pretty new to python and I have a task to complete, but I could not find a way to do it so I'm asking you for help. This is my task: I have to take input from user, for example:
stackoverflow1.2312312321abcd42ds43
and append:
- floating number into floatList
- "42" into evenList
- and 43 into oddList
This is what my code looks like atm:
user_input = input("Please enter the text: ")
Code:
freeText = ""
floatList = []
evenList = []
oddList = []
for i in user_input:
if i.isdigit():
i += freeText
elif i != "":
floatList.append(i)
The main idea is:
Go through the input character by character (as you did with for i in ...)
While you are going through the input, build a string containing the number you have read so far (current_number).
Also, have a boolean variable that states whether the number read so far contains a decimal dot (has_decimal_dot).
If you encounter a digit, just append it to current_number and continue looking at the next character.
If you encounter a dot, also append it to current_number and remember you encountered a dot. Then, continue looking at the next character.
If finally you encounter a character that is not a digit nor a dot, you know the number you were reading has ended.
Then, if you encountered a dot, you know it was a float, so you convert the string to a float and append it to the floatlist.
If you didn't encounter a dot, current_number must be an integer, at least if it has a length > 0. Test modulo 2 to know whether it is even or odd.
After adding the number, you have to prepare for the next one. Set current_number again to an empty string, and has_decimal_dot to False
A trick to not have to do something special for the last number in the string, make sure the string doesn't end with a digit. For example by appending a space.
#user_input = input("Please enter the text: ")
user_input = "stackoverflow1.2312312321abcd42ds43"
# in the beginning, it is easier to test if you don't have to type the input every time
# when everything is working more or less, we can try with input from the user
floatList = []
evenList = []
oddList = []
user_input += " " # add a non-digit at the end so we don't have to handle the last number differently
current_number = ""
has_decimal_dot = False
for i in user_input:
if i.isdigit():
current_number += i # append the character to the string
elif i == ".":
current_number += i
has_decimal_dot = True
else: # not a digit and not a dot
if has_decimal_dot and len(current_number) > 1: # the nunber has a dot, but is not only a dot
floatList.append(float(current_number))
elif len(current_number) > 0: # we encountered a non-digit, and the number we were building is not empty
num = int(current_number)
if num % 2 == 0:
evenList.append(num)
else:
oddList.append(num)
current_number = "" # we just handled the number, now prepare for a next one
has_decimal_dot = False
Homework question is asking me to write a program that would output True if an integer is odd and has the number "0" in the middle of it. I figured out how to get it to print True if a number is odd but can't figure out how to detect if the number 0 is in the middle.
I've figured out the first condition which would be detecting if it's odd.
input:
def is_cyclops(n):
if len(str (n)) % 2 != 0:
return True
return False
print (is_cyclops(11011))
output:
True
I want to know how to get the code to detect the number 0 in the middle.
I'll provide a response in the form of an algorithm:
Convert the number to a string
Detect whether the string has an even or odd number of characters (because even numbered strings don't have a single "middle" character)
Look at the middle character which is character # (len(str)/2)-0.5
That's your middle character
This code will work for an input n.
n = str(n)
if(len(n)%2==0): #Checks if even
if(n[len(n)/2]==0): #Checks for presence of 0
return True
else:
if(n[len(n+1)/2]==0): #Checks for presence of 0
return True
So what i want is for my code to understand if my input has a number in it or not, if it does it is meant to output "Correct" but if it doesn't then it would output "Incorrect" how can i actually make this work. So it knows if there is an integer in the input or not. Any help is appreciated
import re
yourString=input()
number = re.search(r'\d+', yourString).group()
if number == True:
print("Correct")
else:
print("Incorrect")
According to https://docs.python.org/3/library/re.html#match-objects you have a bit of a subtle error.
The statement should not be if number == True: it should be if number:, the reason being the value number is tests as True if anything is matched, and is None if there are no matches.
i.e.
import re
yourString=input()
number = re.search(r'\d+', yourString)
if number:
print("Correct")
group = number.group()
else:
print("Incorrect")
Note, somewhat bizarrely
import re
yourString=input()
number = re.search(r'\d+', yourString)
if number:
print(number == True)
group = number.group()
else:
print("Incorrect")
Prints false, so number is not the value true, it overrides __bool__. See https://docs.python.org/3/reference/datamodel.html#object.bool for more information
You can use str.isdigit, re.search, or the built-in string to number conversions such as float and int:
def extractNumber(string):
for word in string.split():
try:
# The float() function accepts a decimal string.
# The int() function accepts an integer string.
return float(word)
except ValueError:
pass
number = extractNumber(input())
if number is not None:
print('Your number is: {}'.format(number))
else:
print('No number found')
the regex you're looking for is: \w*[0-9]+\w*. It accepts anything that contains at least one digit.
\w* is the same as [a-zA-Z0-9_]* meaning it will match any lower/upper -case letter, digit or _ literally. It can occur 0 to many times in the string
[0-9]+ matches one to many digits from 0 to 9.
Actually, if your intention is just to check whether the string has digits you are good to go just with [0-9]+ that's the same of what you posted originally.
You can try and create regexes using this site regex101.com
I found this practice today:
Detect whether a check number is valid or not. The check number must have 10 digits, can not have 2 or more zeros followed, nor three or more digits other than zero followed
I've able to complete the first part with this code:
num_chk=input('Enter chk number: ')
if (len(num_chk) == 10):
print('valid')
else:
print('not valid')
any thoughts on how to create the logic to check if the check number has 2 consecutive 0.
thanks
You can check if the number has two or more zeroes, or three or more digits by using built-in function any(), for example:
if len(num) == 10:
if any((x in num) for x in [str(i) + str(i) + str(i) for i in range(1, 10)]):
print('invalid')
elif '00' in num:
print('invalid')
else:
print('valid')
else:
print('invalid')
any() returns True if any of the supplied expressions is True.
Let's say your check number is the variable check_number and it is 12300.
check_number = 12300
convert it to a string:
str_check_num = str(check_number)
# str_check_num now equals "12300" a a string
has_00 = "00" in str_check_num
# Returns True if "00" is in str_check_num. in this case it is.
num_chk is type str, which gives you access to:
a in b - return True if string a is in string b, e.g. '00' in num_chk
To check whether the trailing part is some number of zeroes, you can try endswith or look into regular expressions (re package in Python) if you don't know how many zeroes it might be.
A solution with regex for detecting the others condition, as suggested by #Riaz, should be definitely better than what I'm about to suggest, but for the sake of completeness, one can also do the following using itertools.groupby, grouped_L returns a list of tuples with a number followed by it's number of consecutive duplicates (Reference):
from itertools import groupby
num = 1234567890 # Using input as an int
L = [int(x) for x in str(num)]
grouped_L = [(k, sum(1 for i in g)) for k,g in groupby(L)]
validity = True
if len(str(num)) == 10:
for i in grouped_L:
if (i[0]!=0 and i[1]>2):
validity = False
break
elif (i[0]==0 and i[1]>1):
validity = False
break
else:
validity = True
else:
validity = False
if validity:
print('valid')
else:
print('not valid')
something like :
>>> def check(num):
... l=[str(i)+str(i) for i in range(10)]
... l[0]='000'
... if len(num)!=10:
... return "not valid"
... else:
... for i in l:
... if i in num:
... return "not valid"
... return "valid"
...
>>> n="1234567890"
>>> check(n)
'valid'
>>> n="1234500090"
>>> check(n)
'not valid'
If I understand the question ("two or more zeroes followed" means "two or more consecutive zeroes"?), the number must have exactly 10 digits. It must not have two (or more) consecutive zeroes. It must not have three (or more) consecutive digits other than zero. (Three consecutive zeroes implies two consecutive zeroes, so that does constitute an invalid number because of the 2nd rule--we do not need to exclude zero from the last test).
That gives that code
def validate(s):
# 10 characters
if len(s) != 10:
return False
# all digits
for c in s:
if not c.isdigit():
return False
# no two or more consecutive '0'
for a,b in zip(s[0:9],s[1:10]):
if a == b == '0':
return False
# no three or more consecutive digits
for a,b,c in zip(s[0:8],s[1:9],s[2:10]):
if (a == b == c) and a.isdigit():
return False
#
return True
TESTS = (
'12345678x0', # one character not digit
'123456789', # not 10 characters
'1234567890', # valid
'1230067890', # two consecutive zeroes
'1224567890', # valid
'1114567890', # three consecutive digits (other than zero)
)
for t in TESTS:
print( t, 'valid' if validate(t) else 'not valid' )
n = raw_input("Enter number: ")
print( n, 'valid' if validate(n) else 'not valid' )