225k views
3 votes
Write a regular expression pattern that matches strings representing trains. A single 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. 1. One or more Engines appear at the front; one Caboose at the end. 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. These cars cannot appear anywhere other than these locations. Here are some legal and illegal exemplars. EC Legal: the smallest train EEEPPDBBPDBBBBC Legal : simple train showing all the cars EEBB Illegal: no caboose (everything else OK) EBBBC Illegal: three boxcars in a row EEPPPPPDBBC Illegal: more than four passenger cars in a row EEPPBBC Illegal: no dining car after passenger cars EEBBDC Illegal: dining car after box car Hint: my RE pattern was 16 characters.

User XCS
by
5.2k points

1 Answer

4 votes

Answer:

See explaination

Step-by-step explanation:

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

Train EC is valid: True

Train EEEPPDBBPDBBBBC is valid: True

Train EEBB is valid: False

Train EBBBC is valid: False

Train EEPPPPPPDBBC is valid: False

Train EEPPBBC is valid: False

Train EEBBDC is valid: False

User Posha
by
4.6k points