Home > Software design >  Python - join propositions
Python - join propositions

Time:01-03

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?

CodePudding user response:

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)

CodePudding user response:

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)'

CodePudding user response:

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)
  • Related