Finding the Number of Time a Pattern is Inputted Using Python

Finding the Number of Time a Pattern is Inputted Using Python

ECX 30 Days of Code and Design

Day 12

Student or Professor

Task

At a certain school, student email addresses end with @student.college.edu, while professor email addresses end with @prof.college.edu. Write a program that first asks the user how many email addresses they will enter, and then have the user enter those addresses. After all the email addresses are entered, the program should print out a message indicating exactly how many student and professor emails were entered.

Approach

I made use of two different approaches to answer the task. In the first approach, we would use the re module, while we would use the endswith() module.

Using Regular Expression

This is the code. I would explain it in bits throughout this article.


#Using Regular Expressions
import re

print(' Registration Form '.center(40, '*'))
print('Enter the email addresses of your fellow student member(s) and professor(s)')

try:
    num_of_emails = int(input('How many emails are you entering: '))

    email = []                          # List to store user inputs
    compiled_email = ''                 # Variable to store email list converted to string

    for i in range(num_of_emails):
        user_input = input('Email ' + str(i + 1) + ' : ')
        email.append(user_input)        # Add user inputs to list

    compiled_email = ', '.join(email)   # converting list to string, because only allows strings

    # Regex match patterns
    student_email_regex = re.compile(r'\w+@student\.college\.edu')
    prof_email_regex = re.compile(r'\w+@prof\.college\.edu')

    student_match = student_email_regex.findall(compiled_email)
    prof_match = prof_email_regex.findall(compiled_email)

    num_of_student_emails = len(student_match)
    num_of_prof_emails = len(prof_match)

    print('\nNumber of emails entered: ', num_of_emails)
    print('You inputted ' + str(num_of_prof_emails) + ' professors emails')
    print('You inputted ' + str(num_of_student_emails) + ' students emails')

except ValueError:
    print('Invalid input. Enter an integer.')

First, we import the re module and print on the screen instructions for the user to follow.

import re

print(' Registration Form '.center(40, '*'))
print('Enter the email addresses of your fellow student member(s) and professor(s)')

Next, we wrap our code in a try except block to handle value error that would occur if the user inputs any value other than an integer when asked for the number of emails he wants to input.


try:
--snip--
except ValueError:
    print('Invalid input. Enter an integer.')

We then create an empty list, email, where we would store the inputs of the user. The findall() function in the re module takes in strings as its argument, so we would have to convert the list items of email to a string, so we would create a variable, compiled_email to store the string gotten from email list items. Next, we ask the user how many emails he hopes to enter.

try:
    email = []                          # List to store user inputs
    compiled_email = ''                 # Variable to store email list converted to string

    num_of_emails = int(input('How many emails are you entering: '))

Using a for loop, we allow the user enter the number of emails he said he wants to enter. The email.append(user_input) adds the emails to the list. When the user is done and all inputs have been added to the list, we convert the list items to a string using the join() function separating each list item with a comma.

    for i in range(num_of_emails):
        user_input = input('Email ' + str(i + 1) + ' : ')
        email.append(user_input)        # Add user inputs to list

    compiled_email = ', '.join(email)   # converting list to string, because only allows strings

We then created the regex patterns (for the students' and professors' emails) we want to search for. For the students, we have \w+@student\.college\.edu, while for the professors, we have \w+@prof\.college\.edu. In both cases, we first search for words \w+, then the email extension for the students @student\.college\.edu for the student email pattern, and for the professors, the professor extension @prof\.college\.edu. Next, we use the findall() function to search the compiled_email for occurrences of the patterns we hope to match. The findall() function creates a list of all the matches found in its argument.

    student_email_regex = re.compile(r'\w+@student\.college\.edu ')
    prof_email_regex = re.compile(r'\w+@prof\.college\.edu')

    student_match = student_email_regex.findall(compiled_email)
    prof_match = prof_email_regex.findall(compiled_email)

Finally, we find the number of patterns found using the len() function, and we display it to the screen.

    num_of_student_emails = len(student_match)
    num_of_prof_emails = len(prof_match)

    print('\nNumber of emails entered: ', num_of_emails)
    print('You inputted ' + str(num_of_prof_emails) + ' professors emails')
    print('You inputted ' + str(num_of_student_emails) + ' students emails')

Using the Endswith() Method

There are only a few minor differences from the code above.

# Using endswith() method

print(' Registration Form '.center(40, '*'))
print('Enter the email addresses of your fellow student member(s) and professor(s)')

student_email = 0
prof_email = 0

try:
    num_of_emails = int(input('How many emails are you entering: '))

    for i in range(num_of_emails):
        user_input = input('Email ' + str(i + 1) + ' : ')

        if user_input.endswith('@student.college.edu'):
            student_email = student_email + 1
        elif user_input.endswith('@prof.college.edu'):
            prof_email = prof_email + 1

    print('\nNumber of emails entered: ', num_of_emails)
    print('You inputted ' + str(prof_email) + ' professor(s) emails')
    print('You inputted ' + str(student_email) + ' student(s) emails')

except ValueError:
    print('Invalid input. Enter an integer.')

Here, when the user inputs the emails, we check if they either end with @student.college.edu (for which we increment the variable, student_email) or if they end with @prof.college.edu (for which the prof_email is incremented)

student_email = 0
prof_email = 0if user_input.endswith('@student.college.edu'):
            student_email = student_email + 1
        elif user_input.endswith('@prof.college.edu'):
            prof_email = prof_email + 1

Run the regex solution.
Run the endswith() solution.