Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

hi guys i need to write a small function in python that will take a list of term

ID: 639204 • Letter: H

Question

hi guys i need to write a small function in python that will take a list of terminals and a string as inputs, and split the string by terminals. so say terminals=['true','/','false'] and string="false false/true", output should be 'false', 'false','/','true'. I have trouble writing a regular expression, i don't know how to incorporate a loop that would go through every element of terminals import re def tokenize(terminals,stringline): tokens = [t for t in re.split(r"(s+|true|false|)")] can please give me any hints?

Explanation / Answer

Python Porgram:

>>> def tokenize(terminals,stringline):
regex='|'.join(terminals)
return [i for i in re.split('('+ regex + ')' +r'|s+', stringline) if i is not None and i]

>>> terminals=['true','/','false']
>>> string="false false/true"
>>> tokenize(terminals, string)
['false', 'false', '/', 'true']