Answer:
See explaination
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