python - Searching for a sequence in a text -
i have run logic problem.
i have string declared follows:
fruits = "banana grapes apple" vegetables = "potatoes cucumber carrot"
now there text sentences, , have search word in front of text format <vegetables> <fruits>
i ate carrot grapes ice cream dessert.
answer : ate
dad , mom brought banana cucumber , milk.
answer : brought
what thinking split sentence , put in array, , sequence, able break sentence matching sequence problem.
wd = sentence.split(' ') x in wd.strip().split(): # have sequence
now, have text in front of text format
you're using wrong data-structures here, convert fruits , vegetables sets. problem easy solve:
>>> fruits = set("banana grapes apple".split()) >>> vegetables = set("potatoes cucumber carrot".split()) >>> fruits_vegs = fruits | vegetables >>> string import punctuation def solve(text): spl = text.split() #use itertools.izip , iterators memory efficiency. x, y in zip(spl, spl[1:]): #strip off punctuation marks x,y = x.translate(none, punctuation), y.translate(none, punctuation) if y in fruits_vegs , x not in fruits_vegs: return x ... >>> solve('i ate carrot grapes ice cream dessert.') 'ate' >>> solve('dad , mom brought banana cucumber , milk.') 'brought' >>> solve('banana cucumber , carrot.') 'and'
Comments
Post a Comment