Advertisement
Guest User

Print Segment Code

a guest
May 22nd, 2013
278
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.70 KB | None | 0 0
  1. def printvalidsegments(string,wset):
  2.     # 'wset' gives the set of valid words
  3.     # 'string' is the string to be segmented
  4.    
  5.     valid = 0   # index till which it has been validified
  6.     last_letter_index = len(string)
  7.        
  8.     vseglist = [] #list storing all valid segments
  9.     segflag = False #indicating whether any valid segment has been found
  10.     while valid != last_letter_index :
  11.         ran = xrange(last_letter_index,valid,-1)
  12.         for i in ran:
  13.             if string[valid:i].lower() in wset:
  14.                    
  15.                 segflag = True #valid segmnt has been found
  16.                 #print "debug:segment",string[valid:i],valid,i
  17.                 vseglist.append(string[valid:i]) #segmnt has been added to list
  18.                 valid = i
  19.                 break
  20.                
  21.             if i == (valid+1):
  22.                 for seg in vseglist: #backtracking: try removing one valid segment from wset and hence continue
  23.                     #print "debug:first",seg
  24.                     wset.remove(seg.lower())
  25.                     if printvalidsegments(string,wset):
  26.                         return True
  27.                     wset.add(seg.lower())
  28.                    
  29.                 valid = last_letter_index
  30.                 return False
  31.     print  " ".join(vseglist)
  32.     return True
  33.  
  34. def main():
  35.     string = "artisteer"
  36.     wset = set(['art','i','steer','artist','a','sign','as'])
  37.     if printvalidsegments(string,wset) == False:
  38.         print "error"
  39.  
  40.     string = "asignas"    
  41.     if printvalidsegments(string,wset) == False: #prints error instead of valid segments "a sign as"
  42.         print "error"
  43.        
  44.        
  45. if __name__ == '__main__':
  46.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement