Skip to content

Instantly share code, notes, and snippets.

@svalleru
Last active October 16, 2015 19:39
Show Gist options
  • Save svalleru/bbaae89dbee974b2ba6b to your computer and use it in GitHub Desktop.
Save svalleru/bbaae89dbee974b2ba6b to your computer and use it in GitHub Desktop.
SentenceCheck
#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