Last active
October 16, 2015 19:39
-
-
Save svalleru/bbaae89dbee974b2ba6b to your computer and use it in GitHub Desktop.
SentenceCheck
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #Given a dictionary and a string, check if the string forms a proper sentence | |
| ''' | |
| thisisasentence -> True | |
| thisisnotasantance -> False | |
| ''' | |
| dictionary = set([ | |
| 'this', | |
| 'is', | |
| 'a', | |
| 'i', | |
| 'sentence', | |
| ]) | |
| match_bkt = [] | |
| # ip_str = 'sentence' | |
| # ip_str = 'thisisnotasentence' | |
| ip_str = 'thisisasentence' | |
| # ip_str = 'isa' | |
| def sentence_chk(ip_list): | |
| for i in xrange(1, len(ip_list) + 1): | |
| sub_str = ''.join(ip_list[:i]) | |
| if sub_str in dictionary: | |
| # push to match_bkt | |
| match_bkt.append(sub_str) | |
| if len(ip_list[i:]) > 0: | |
| if sentence_chk(ip_list[i:]) is not True: | |
| # pop match_bkt & backtrack | |
| match_bkt.pop() | |
| continue | |
| else: | |
| sentence_chk(ip_list[i:]) | |
| if len(''.join(match_bkt)) == len([o for o in ip_str]): | |
| print ip_str, '-- is a sentence' | |
| exit() | |
| ip_list = [i for i in ip_str] | |
| if sentence_chk(ip_list) is None: | |
| print ip_str, '-- is not a sentence' | |
| #Note to the sheeple: this code can be further optimized |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment