Preliminaries For this lab you will be working with regular expressions in Pytho
ID: 3814845 • Letter: P
Question
Preliminaries
For this lab you will be working with regular expressions in Python. Various functions for working with regular expressions are available in the re module. Fortunately, Python makes it pretty easy to see if a string matches a particular pattern.
At the top of the file we must import the re module: import re
Then we can use the search() function to test whether a string matches a pattern. In the example below, the regular expression has been saved in a string called pattern for convenience:
The r that precedes the pattern string is not a typo. Rather, the r indicates that the string is a “raw” string. In a raw string, as opposed to a “normal” string, any backslash character is interpreted as simply a backslash, as opposed to defining an escape sequence like or . Make sure you use raw strings in your Python code when defining regular expressions.
The ˆ and $ at the beginning and end of the regular expression indicate that the entire string must match the regular expression, and not just part of the string. Make sure you include these symbols in your regular expressions too!
Write a function enrollments() that takes a list of strings representing course IDs (e.g., “CSE 220”) and returns a count of how many strings define valid courses. Courses should be expressed as a three-letter subject in mixed uppercase/lowercase letters, followed by an optional space, followed by a three-digit number. So, ideally, each course is given in a form similar to "CSE 101" or "Phy 132". One obstacle to solving this problem is that sometimes extra characters – specifically, combinations of periods, dashes and commas – are inadvertently inserted in between letters. In such cases we still consider the course IDs to be valid.
Examples: Function Call Return Value enrollments (ICSE 101 AMS 310' PHY 132', 'Wrt 102 J) 4 enrollments CSE114', ECO330', 'CHNN 101', 'Ams 261', MAT 200', 'WRT101', frn1012', che 299' enrollments C-S 14 C. S E215 AMS-211 B, I. O 255 CO 102Explanation / Answer
import re
def enrollments(courses):
#write your code here
pattern = r'^[A-Za-z][-,.]?[A-Za-z-,.]?[A-Za-z][ ]?d{3}'
count =0
for x in courses:
xlen =len(''.join(e for e in x if e.isalnum()))
if xlen==6:
if re.search(pattern, x):
count = count +1
return count
if __name__ == '__main__':
courses1 = ['CSE 101', 'AMS 310', 'PHY 132', 'Wrt 102']
courses2 = ['CSE114', 'ECO330', 'CHNN 101', 'Ams 261', 'MAT 200', 'WRT101', 'frn1012', 'che 299']
courses3 = ['C-S-E 114', 'C.S..E215', 'AMS-211', 'B,,,I.-O 255', '-ECO 102']
print('Test enrollments() with courses = ' + str(courses1))
print(' Return value: ' + str(enrollments(courses1)))
print('Test enrollments() with courses = ' + str(courses2))
print(' Return value: ' + str(enrollments(courses2)))
print('Test enrollments() with courses = ' + str(courses3))
print(' Return value: ' + str(enrollments(courses3)))