Python - join propositions

56 views Asked by At

I have an list of strings which illustrate propositions. E.g.

L = ['(A∧B)', 'A', 'B']

My aim is to join each element with the string '∧' and brackets "()", which results in following string:

aim = "(((A ∧ B) ∧ A) ∧ B)"

is their a simple method to do that?

3

There are 3 answers

0
Corralien On BEST ANSWER

Use reduce from functools module:

from functools import reduce

aim = reduce(lambda l, r: f"({l} ^ {r})", L)
print(aim)

# Output
(((A∧B) ^ A) ^ B)
0
Ajax1234 On

You can use recursion:

def jn(d):
  return '('+' ∧ '.join(([d.pop()]+[d[0] if len(d)==1 else jn(d)])[::-1])+')'

print(jn(L))

Output:

'(((A∧B) ∧ A) ∧ B)'
0
S P Sharan On

Really straightforward answer

l = ["(A^B)", "A", "B"]
l = [each[1:-2] if each[0] == "(" else each for each in l] # Remove brackets if they exist
output = "(" * len(l) + ") ^ ".join(l) + ")" # Join
print(output)

Output

(((A^) ^ A) ^ B)