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
Related
When I'm asked to write in my function a code to count the characters of a code but only if its a multiple of three, i keep getting stuck and i've tried so many times to figure it out but to no avail!
This was the question: ...verifies that its length is a multiple of 3, and returns the number of codons in that string...
I tried this:
def countCodons(DNA):
count = 0
for num in DNA:
if len(num) % 3 == 0:
count += 1
return len(DNA)
else:
return False
assert countCodons("CATGGG") == 2
assert countCodons("CAATGGG") == False
But I keep getting an error. When i just put in "countCodons" I keep getting False.
You are making this too complicated. The function needs to do two things:
determine if the length of the input string is a multiple of 3
if so, return the length of the input string divided by 3
You were right in assuming that you can use ... % 3 == 0 somehow but you were not applying it correctly. You don't need a for loop, which iterates over the individual characters in the string. Just apply it on the length of the string directly.
Regarding 2., even if you had managed to count the characters in the input string, you forgot to divide by 3.
Here's a straightforward solution:
def countCodons(DNA):
if len(DNA) % 3 == 0: # length is a multiple of 3
return len(DNA) // 3
else:
return False
Note that // is used to return an integer result, rather than a floating-point result (see Python Tutorial).
Alternatively you could use the divmod function which combines the integer division with remainder in one step:
def countCodons(DNA):
count, remainder = divmod(len(DNA), 3)
if remainder == 0:
return count
else:
return False
This assertion fails because the return statement is within the loop and only returns the length of the input string, not the count of codons. So, it will always return the length of the input string, even if there are no codons in the input string.
assert countCodons("CAATGGG") == False
This assertion succeeds because the first element in the input string is not a multiple of 3, so the function returns False.
To fix this issue, the return statement should be outside the loop and return the count of codons. Here's the corrected code:
def countCodons(DNA):
count = 0
for num in DNA:
if len(num) % 3 == 0:
count += 1
return count if count > 0 else False
This code will now correctly return the count of codons in the input string.
def main():
plate = input("Plate: ")
if is_valid(plate):
print("Valid")
else:
print("Invalid")
def is_valid(s):
#vanity plates may contain a maximum of 6 characters (letters or numbers) and a minimum of 2 characters.
if 2 > len(s) > 6:
return False
#All vanity plates must start with at least two letters.
if s[0].isalpha() == False or s[1].isalpha() == False:
return False
#Numbers cannot be used in the middle of a plate; they must come at the end.
#The first number cannot be 0
i = 0
while i < len(s):
if s[i].isalpha() == False:
if s[i] == '0':
return False
else:
break
i += 1
#No periods, spaces, or punctuation marks are allowed.
if s.isalpha() == False or s.isinstance() == False:
return False
#passes all requirements
return True
main()
The regular expression module provides an easy way to approach what you intend to achieve with the code provided in your question. The code below should do what you intend to achieve, so try it out:
import re # regular expressions module
# All vanity plates must start with at least two letters.
# Numbers cannot be used in the middle of a plate; they must come at the end.
# The first number cannot be 0
rexp = re.compile('^[a-zA-Z]{2,6}([1-9][0-9]*)?')
def main():
plate = input("Plate: ")
# e.g. plate = "plat01"
if is_valid(plate):
print("Valid")
else:
print("Invalid")
def is_valid(s):
l = len(s)
#vanity plates may contain a maximum of 6 chars (letters or numbers)
# and a minimum of 2 characters.
if 2 > l or l > 6:
return False
if rexp.match(s).span() == (0,l):
return True
return False
main()
P.S. Check out https://regex101.com/r/LNw2pW/1 for detailed explanations of the used regular expression pattern. The 'trick' is to check if the found match length is the same as the length of the input string. If yes, than the input string is valid.
From the code above I see that you use isinstance() incorrect.
Try changing s.isinstance() == False to isinstance(s, type) == False, and choose the type you want to check (int, str.. etc)
Reference:
https://www.w3schools.com/python/ref_func_isinstance.asp
My program tries to guess if an input number or letter is in a specific string. For that I have this simplified piece of code:
obtained = False
for i in range(6+len(chosen_set)):
try_let = input("Input something")
for index, letnum in enumerate(chosen_set):
if letnum == try_let:
obtained = True
else:
obtained = False
if obtained:
# do something
else:
# do something else
Say I input the letter "R" and the string I'm testing is XXXRXRX. When the inner for loop goes through its 4th iteration, the variable obtained will be True, and the same will happen for the 6th iteration, but not for the last one, which means the final value of obtained will be False. How should I change my code so that obtained will be True as long as it finds a coincidence regardless of when it finds it? Note that I can't use break in the for loop as soon as it finds a coincidence because the string could have more than one coincidence.
Maybe that?
for i in range(6+len(chosen_set)):
try_let = input("Input something")
obtained = False
for index, letnum in enumerate(chosen_set):
if letnum == try_let:
obtained = True
if obtained:
# do something
else:
# do something else
If you can't use a break, then change the logic of using an explicit True/False boolean as the primary decision factor and make use of a count as well.
For example:
count=0
if letnum == try_let:
count+=1
if count > 0:
obtained = True
else:
obtained = False
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
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