Home > Mobile >  How to implement a loop wherein: Numbers cannot be used in the middle of the input; they must come a
How to implement a loop wherein: Numbers cannot be used in the middle of the input; they must come a

Time:06-19

def main():
    plate = input("Plate: ")
    if is_valid(plate):
        print("Valid")
    else:
        print("Invalid")


def is_valid(s):

# All vanity plates must start with at least two letters
    if s[0].isalpha() == False or s[1].isalpha() == False:
        return False

# vanity plates may contain a maximum of 6 characters (letters or numbers) and a minimum of 2 characters
    if len(s) < 2 or len(s) > 6:
        return False

# Numbers cannot be used in the middle of a plate; they must come at the end

# TODO



# No periods, spaces, or punctuation marks are allowed
    for c in s:
        if c in [".", " ", ",", "!", "?"]:
            return False

# PASSES ALL TESTS
    return True


main()

Here's my project on Vanity Plates request... there are certain criteria for the input, all of which except one has been successfully implemented. Kindly help me out with the one stating "Numbers cannot be used in the middle of a plate; they must come at the end".

CodePudding user response:

Here is how you might do it:

def is_valid(s):
    if not (2 <= len(s) <= 6):
        return False
    if not s[:2].isalpha():
        # If the first two characters are not letters, it is invalid
        return False
    any_numbers = False
    for c in s:
        if c.isdigit():
            if c=='0' and not any_numbers:
               # 0 cannot be the first digit
               return False
            any_numbers = True
        elif c.isalpha():
            if any_numbers:
                # If a letter comes after a number, it is invalid
                return False
        else:
            # If the character is not a letter or number, it is invalid
            return False
    return True

CodePudding user response:

first check if the first and second number is digit, if yes then false next check if length is minimum 2 and maximum 6 else false third check if starting from first number, end is number else False

number = "A2AA222"


def is_valid(number):
    if not 2 <= len(number) <= 6:
        return False
    elif number[0].isdigit() or number[1].isdigit():
        return False
    elif not number[:2].isalpha():
        return False    

    first_number = [num for num in number if num.isdigit()][0]
    first_number = number.index(first_number)
    number_list = number[first_number:]

    if number_list.isdigit():
        return True
    else:
        return False

is_valid(number)
  • Related