PYTHON PROBLEM 2. (5 pts) Write a regular expression patterm that matches string
ID: 3596597 • Letter: P
Question
PYTHON PROBLEM
2. (5 pts) Write a regular expression patterm that matches strings representing trains. Asingle letter stands for each kind of car in a train: Engine, Caboose, Boxcar, Passenger car, and Dining car. There are four rules specifying how to form trains legally 1. One or more Engines appear only at the front; one Caboose only at the end. All other cars are between these. 2. Boxcars always come in pairs: BB, BBBB, etc. 3. There cannot be more than four Passenger cars in a series. 4. One Dining car must follow each series of Passenger cars (and occur no where else). These cars cannot appear anywhere other than these locations. Here are some legal and illegal exemplars. See more legal/illegal examples in bm2a.txt. BC Legal: the smallest train EEEPPDBBPDBBBBC EEBB EBBBC BBPPPPPDBBC EBPPBBC EEBBDC Legal : simple train showing all kinds of cars Ilegal: no caboose (everything else OK) Ilegal: three (odd number of) boxcars in a row Illegal: more than four passenger cars in a Ilegal: no dining car after passenger cars Ilegal: dining car after box carExplanation / Answer
import re
def isValidTrain(train):
pattern = r'^E+(((P|PP|PPP|PPPP)D)*(BB)*)*C$'
if re.match(pattern, train):
return True
return False
def checkAndPrintTrain(train):
print("Train", train, "is valid:", isValidTrain(train))
checkAndPrintTrain("EC")
checkAndPrintTrain("EEEPPDBBPDBBBBC")
checkAndPrintTrain("EEBB")
checkAndPrintTrain("EBBBC")
checkAndPrintTrain("EEPPPPPPDBBC")
checkAndPrintTrain("EEPPBBC")
checkAndPrintTrain("EEBBDC")
Sample output
# copy pastable codE: https://paste.ee/p/OHXjO
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.