1

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?

Martin Kunze
  • 995
  • 6
  • 16

3 Answers3

1

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)'
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
1

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)
Corralien
  • 109,409
  • 8
  • 28
  • 52
1

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)
S P Sharan
  • 1,101
  • 9
  • 18