I'd like to create an algorithm that takes as input a propositional logic expression without parentheses and outputs the same expression enclosed in parentheses in all possible ways depending on the logical connectives present. For example, if I have "p and q or r implies not s" as input I should obtain ((p and (q or r)) implies (not s): here's my code:
def parenthesize(expression):
# Define a list of logical connectives
connectives = ["and", "or", "not", "implies", "if and only if"]
# Base case: if the expression is a single variable, return it enclosed in parentheses
if expression not in connectives and len(expression.split()) == 1:
return "(" + expression + ")"
# Recursive case: find the outermost connective and apply the algorithm to each sub-expression
nesting_levels = [0] * len(expression)
stack = []
for i, char in enumerate(expression):
if char == "(":
stack.append(i)
elif char == ")":
j = stack.pop()
nesting_levels[j:i+1] = [len(stack)] * (i-j+1)
max_nesting_level = max(nesting_levels)
outermost_connectives = [connectives[i] for i, level in enumerate(nesting_levels) if level == max_nesting_level]
if len(outermost_connectives) == 1:
connective = outermost_connectives[0]
subexpressions = expression.split(connective)
parenthesized_subexpressions = [parenthesize(subexpression) for subexpression in subexpressions]
return "(" + connective.join(parenthesized_subexpressions) + ")"
else:
# If there are multiple outermost connectives, choose the first one
connective = outermost_connectives[0]
index = expression.index(connective)
left_expression = expression[:index].strip()
right_expression = expression[index+len(connective):].strip()
parenthesized_left_expression = parenthesize(left_expression)
parenthesized_right_expression = parenthesize(right_expression)
return "(" + parenthesized_left_expression + " " + connective + " " + parenthesized_right_expression + ")"
# Example usage
expression = "p and q or r implies not s"
parenthesized_expression = parenthesize(expression)
print(parenthesized_expression)
Problem is my output is wrong: it's "(p and q or r implies not s)", could someone lead me to a solution? Thanks