Last active
September 2, 2018 00:31
-
-
Save vrjkmr/44e941e906124e1e371d7cb23a18161c to your computer and use it in GitHub Desktop.
Boolean text which returns a list prepared for a binary tree structure.
This file contains 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
def parse(expr): | |
expr = expr.replace('(', ' ( ').replace(')', ' ) ') | |
brac_just_opened = False | |
def _listify(iter): | |
nonlocal brac_just_opened | |
items = [] | |
for item in iter: | |
if item == '(': | |
brac_just_opened = True | |
result, closeparen = _listify(iter) | |
items.append(result) | |
elif item == ')': | |
if len(items) == 1: | |
return items[0], True | |
else: | |
return items, True | |
elif item == 'NOT': | |
if brac_just_opened: | |
result, closeparen = _listify(iter) | |
items.append(['NOT', result]) | |
else: | |
result, closeparen = _listify(iter) | |
items.extend(['NOT', result]) | |
else: | |
items.append(item) | |
if len(items) == 1: | |
return items[0], False | |
else: | |
return items, False | |
listified_expr = _listify(iter(expr.split()))[0] | |
def _prefixify(lst): | |
if len(lst) > 1: | |
if len(lst) == 2: | |
return lst | |
if len(lst) % 2 == 1: | |
odds = lst[1::2] | |
if odds.count(odds[0]) == len(odds): | |
return [odds[0]] + lst[0::2] | |
else: | |
return 'ERROR' | |
def _convert_to_prefix_notation(lst): | |
res = [] | |
prefix_lst = _prefixify(lst) | |
list_idxs = [i for i in range(len(prefix_lst)) if isinstance(prefix_lst[i], list)] | |
if len(list_idxs) > 0: | |
for i in range(len(prefix_lst)): | |
if i in list_idxs: | |
res.append(_convert_to_prefix_notation(prefix_lst[i])) | |
else: | |
res.append(prefix_lst[i]) | |
if i == len(prefix_lst) - 1: | |
return res | |
else: | |
return prefix_lst | |
if isinstance(listified_expr, list): | |
return _convert_to_prefix_notation(listified_expr) | |
else: | |
return [listified_expr] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment