Skip to content

Instantly share code, notes, and snippets.

@remram44
Created April 9, 2013 19:25
Show Gist options
  • Select an option

  • Save remram44/5348598 to your computer and use it in GitHub Desktop.

Select an option

Save remram44/5348598 to your computer and use it in GitHub Desktop.
# S -> aSa | aa
def S(s, pos, depth):
orig = pos
# Try aSa
print "%strying aSa @%d" % (' '*depth, pos)
pos = a(s, pos, depth+1)
if pos is not None:
pos = S(s, pos, depth+1)
if pos is not None:
pos = a(s, pos, depth+1)
if pos is not None:
print "%sgot it, span: %r-%r" % (' '*depth, orig, pos)
return pos
print "%sfailed" % (' '*depth,)
pos = orig
# Try aa
print "%strying aa @%d" % (' '*depth, pos)
pos = a(s, pos, depth+1)
if pos is not None:
pos = a(s, pos, depth+1)
if pos is not None:
print "%sgot it, span: %r-%r" % (' '*depth, orig, pos)
return pos
print "%sfailed" % (' '*depth,)
# Fail
return None
def a(s, pos, depth):
if pos >= len(s):
return None
if s[pos] == 'a':
return pos + 1
return None
def test(s):
pos = S(s, 0, 0)
if pos != len(s):
print '%s fail' % s
else:
print '%s accepted' % s
if __name__ == '__main__':
#test('aa')
#test('aaaa')
test('aaaaaa')
#test('aaaaaaaa')
@remram44
Copy link
Copy Markdown
Author

remram44 commented Apr 9, 2013

Question: http://ideone.com/Dkfa8o, posted on freenode/#programming 2013-04-09

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment