Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def printvalidsegments(string,wset):
- # 'wset' gives the set of valid words
- # 'string' is the string to be segmented
- valid = 0 # index till which it has been validified
- last_letter_index = len(string)
- vseglist = [] #list storing all valid segments
- segflag = False #indicating whether any valid segment has been found
- while valid != last_letter_index :
- ran = xrange(last_letter_index,valid,-1)
- for i in ran:
- if string[valid:i].lower() in wset:
- segflag = True #valid segmnt has been found
- #print "debug:segment",string[valid:i],valid,i
- vseglist.append(string[valid:i]) #segmnt has been added to list
- valid = i
- break
- if i == (valid+1):
- for seg in vseglist: #backtracking: try removing one valid segment from wset and hence continue
- #print "debug:first",seg
- wset.remove(seg.lower())
- if printvalidsegments(string,wset):
- return True
- wset.add(seg.lower())
- valid = last_letter_index
- return False
- print " ".join(vseglist)
- return True
- def main():
- string = "artisteer"
- wset = set(['art','i','steer','artist','a','sign','as'])
- if printvalidsegments(string,wset) == False:
- print "error"
- string = "asignas"
- if printvalidsegments(string,wset) == False: #prints error instead of valid segments "a sign as"
- print "error"
- if __name__ == '__main__':
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement