pythonlistmethodscnf

Python List Indexing and Returning the Item


So this is a simple question that I seem to be confused on, i've been working on this input problem and trying to store certain parts of a users input into segmented lists.

The user input is going to input a CNF (conjunctive normal form). Example: + = or, * = and, anything within the ( and ) is a clause

(A+B)*(C+D)

So since this input has two clauses I need to store each clause as their own item into a list. I'm having trouble figuring how to traverse through the list I have already made and getting my if statement to segment each clause, I understand logically how it's supposed to work, I just need help with syntax and methods associated with storing something dynamically into a list.

I understand whole heartedly why the index is not working, i'm basically looking for the reverse of what index method is, i need to find my item associated with my index.

For example, when I find an open paranthesis "(" i need to start to store a new clause into my list, so far I only found how to return the index itself and not the item via the index. This should be a simple solution to this but I simply can't find anything that associated with displaying this method wise.

cnf = input("CNF: ")
cnf_input = list(cnf)

cnf_input_len = len(cnf_input)
i = 0
##this count resets when it sees a ")"
claus_count = 0
while i < cnf_input_len:

    claus_list = cnf_input.append(i)
    print(cnf_input.index("B"))
    if cnf_input.index(i)=="(":
        print('Cut here')
    i=i+1

My code as a guideline


Solution

  • It seems you are over complicating it. Simply use str.split followed by str.strip to get the individual clauses in a list

    >>> [elem.strip('()') for elem in "(A+B)*(C+D)".split("*")]
    ['A+B', 'C+D']
    

    You can even extend it to get the individual literals of the clauses as a tuple or lists to get a list of lists

    >>> [elem.strip('()').split('+') for elem in "(A+B)*(C+D)".split("*")]
    [['A', 'B'], ['C', 'D']]
    

    You may even want to experiment with regex

    >>> re.findall(r'([^()]+?)\+([^()]+?)', "(A+B)*(C+D)")
    [('A', 'B'), ('C', 'D')]