+ 3
module 9 help plz
hey ppl, i need help with this module 9 test. i passed the first test case, then the 2nd one is not valid, but i fixed to pass the 2nd one, the first case became invalid. here's my code. thx alot [p/s: i tried to look for helps on Stack Overflow and G4G (the codes i basically copied it from G4G, so uh... yea...), but nothing come outs as results, other than some very high technical ones] import re #your code goes here def isValid(s): # 1) Begins with 1 or 8 or 9 # 2) Then contains 8 digits Pattern = re.compile("(1/8/9)?[0-9]{8}") return Pattern.match(s) #prints s = "57345672" if (isValid(s)): print ("Valid") else : print ("Invalid")
7 Réponses
+ 5
pattern for 1, 8 or 9 digit in regex should be [189] (without | as regex character class), then number (either \d or [0-9]) should be repeated only 7 times (as first digit is already checked)...
in addition, you must at least add the end of string anchor ($), to check that string is not larger than 8 (and start of string anchor '^' if you use search instead of match):
import re
pat = re.compile("[189]\d{7}quot;)
def isValid(s):
return pat.match(s)
inp = input() # don't hardcode input: your program should work for any test case ;P
if (isValid(inp)):
print("Valid")
else:
print("Invalid")
+ 2
In your regex "(1/8/9/)?[0-9]{8}",
=> "? " checks if string"1/8/9"is there or not.it will proceed to check further even if it doesn't match the above string. And i think you meant to use "|" For "or" . You might also want to check if the length of number is 9 as regex won't check that for you , i corrected the code as following ,
import re
#your code goes here
def isValid(s):
# 1) Begins with 1 or 8 or 9
# 2) Then contains 8 digits
Pattern = re.compile("[1|8|9][0-9]{8}")
return Pattern.match(s)
#prints
s = "757345672"
if len(s)==9 and (isValid(s)):
print ("Valid")
else :
print ("Invalid")
Let me know if it doesn't works.
+ 2
thx for ur reply, but test case 1 didn't qualified (it returned Invalid when it is supposed to be Valid, 2nd case is still on Invalid)
+ 2
Abhay not in character class ^^
0
yee, thx alot m8
0
I thought | stands for or!!
- 1
Patterns must be as follows
import re
def isValid(s):
pattern = re.compile("^[189]\d{8}quot;)
return re.match(pattern, s)
s = input()
if isValid(s):
print("Valid")
else:
print("InValid")
Inputs:
1) 126543238
2) 543873245
3) 823452363
Above test case
Outputs:
1) Valid
2) InValid
3) Valid
This logic will match exact nine digits and start with digit 1, 8, 9
And re.match(pattern, s) will return 1 match if there are 9 digits as input with preceding digits 1, 8 and 9.
else return's 0 (zero) match.
DHANANJAY