Answer to Question #337085 in Python for Venkatesh Reddy

Question #337085

you are working as a freelancer. A company approached you and asked to create an algorithm for username validation. The company said that the username is string S .You have to determine of the username is valid according to the following rules.

1.The length of the username should be between 4 and 25 character (inclusive).

2.Valid username must start with a letter.

3 Valid username can only contain letters, numbers, and underscores characters.

4 Valid username cannot ends with the underscore character and also doesn't accept the special characters.


INPUT: The first line contains an integer T representing the number of test cases.

The first line of each test cases input contains a string.


OUTPUT: Each test case gives a Boolean value as output(true or false)


sample Input:

3

google

Google_123

google@123


sampleOutput

true

true

false

sample input 2

HelloPython

#Coder

CoderIt

sampleoutput 2

true

false

true



1
Expert's answer
2022-05-04T12:39:03-0400
import re

#length
def rules_1(username):
    if (len(username) >= 4) & (len(username) <= 20):
        return True
    else:
        return False

# start with a letter
def rules_2(username):
    reg = "^([A-Za-z])"
    pat = re.compile(reg)
    mat = re.search(pat, username)
    if mat:
        return True
    else:
        return False

#only contains letters, numbers and underscores character
def rules_3(username):
    pattern = "^[A-Za-z0-9_]*$"
    state = bool(re.match(pattern, username))

    if state:
        return True
    else:
        return False

#cannot ends with the underscore and special characters
def rules_4(username):
    reg = "(?<![_.])$"
    #reg = "(?<![_.])$"
    pat = re.compile(reg)
    mat = re.search(pat, username)
    if mat:
        return True
    else:
        return False


def main():
    t = int(input("Enter T: "))
    names = []
    for i in range(t):
        names.append(input())
    for i in range(t):
        if rules_1(names[i]) & rules_2(names[i]) & rules_3(names[i]) & rules_4(names[i]):
            print(True)
        else:
            print(False)

if __name__ == '__main__':
    main()

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS