Ad

How Can I Append A Value Replacing Multiple Elements In A List?

- 1 answer

I'm trying to make a search system that finds the search keyword containing mutiple ANDs, ORs, and parentheses. What I'm trying to do now is replacing the parenthesis with boolean values. So if I have a list ["A", "or", "(", "B", "and", "C", ")"] , I want to change this list to ["A", "or", True].

First, I've tried the del keyword then append the boolean value like the code below. This works this only example. However I might have parenthesis in the front or middle of the list, and in this case it doesn't work.(because the append keyword always adds elements to the end)

Also I've tried the replace keyword but this returned the output ["A", "or", "T", "r", "u", "e"]

How can I replace ["(", "B", "and", "C", ")"] to True?

sentence = ["B", "C", "D"]
search = ["A", "or", "(", "B", "and", "C", ")"]
if "(" in search:
    start = search.index("(")
    end = search.index(")")
    bracket = search[start + 1 : end]

    if "and" in bracket:
        index_of_and = bracket.index("and")
        if bracket[index_of_and - 1] and bracket[index_of_and + 1] in sentence:
            print("both in")
            bracket = 'True'
        else:
            print("only one or nothing in")
            bracket = 'False'
    elif "or" in bracket:
        index_of_or = bracket.index("or")
        if   bracket[index_of_or -1]  in sentence or  bracket[index_of_or +1]   in sentence:
            bracket = 'True'
        else:
            bracket = 'False'
    else:
        if bracket[0] in sentence:
            bracket = 'True'
        else:
            bracket = 'False'

    del search[start:end+1]
    search = search.append(bool(bracket))
Ad

Answer

your code is a little hard to read but i think its only issue is the append at the end, since you dont know that the closing bracket is the end of the sentence appending can mangle your logic, instead you should insert and the append operation doesnt return anything so this line:

search = search.append(bool(bracket))

should be

search.insert(start - 1, bool(bracket))

I'm also unsure how you managed to get true to be split letter wise, that should only happen if you do list("true")

Ad
source: stackoverflow.com
Ad