• + 0 comments

    regex_integer_in_range = r"^[1-9][0-9]{5}$"

    ^: Matches the beginning of the string. This is crucial to prevent matching substrings within a longer string.

    [1-9]: Matches a single digit from 1 to 9. This ensures the first digit is not 0, fulfilling the 100000 minimum.

    [0-9]{5}: Matches exactly five digits from 0 to 9. This, combined with the previous part, makes sure the number has exactly 6 digits.

    $: Matches the end of the string. This, along with ^, enforces that the entire string must match the pattern, not just a part of it.

    This regex correctly checks for a 6-digit number starting with a digit between 1 and 9, thus covering the range 100000 to 999999 inclusive.

    regex_alternating_repetitive_digit_pair = r"(\d)(?=\d\1)"

    (\d): Matches any digit (0-9) and captures it into group 1. The parentheses are essential for the backreference later.

    (?=...): This is a positive lookahead assertion. It checks if the following part matches, but without including it in the overall match. This is critical for finding overlapping pairs.

    \d: Matches any digit. This is the digit between the repeating ones.

    \1: This is a backreference to the first capturing group (the (\d) at the beginning). It matches the same digit that was captured in group 1.

    This regex cleverly finds alternating repetitive digits. It captures a digit, then looks ahead to see if the next digit is followed by the same digit that was captured. The lookahead is key because it allows the regex engine to find overlapping pairs (e.g., in "12121", it will find "121" and "212").

    import re: Imports the regular expression module.

    P = input(): Reads the input string (the postal code) from standard input.

    print(...): This line performs the final check:

    re.match(regex_integer_in_range, P): Checks if the input P is a valid integer in the specified range. re.match() only matches at the beginning of the string (which is what we want here, thanks to the ^ in our regex).

    len(re.findall(regex_alternating_repetitive_digit_pair, P)) < 2: re.findall() finds all non-overlapping matches of the alternating repetitive digit pattern and returns them as a list. len() gets the number of matches (the number of pairs). The code checks if this count is less than 2 (meaning there are 0 or 1 such pairs).

    and: Combines the two conditions. The postal code is valid only if both conditions are true.

    bool(...): Converts the result of the and operation to a boolean (True or False).

    print(...) then outputs the result to the console.