0

括弧を文に戻して、整形式の式 (センテンシャル ロジックの WFF) にするプログラムを作成しています。例えば、

    - 文aは WFF です。
    - 文a > bには、括弧を元に戻して WFF にする方法が 1 つしかありません(a > b)
    - 文a > b > cには、WFF にするために括弧を復元する 2 つの方法があり((a > b) > c)ます(a > (b > c))
等...

このアルゴリズムには反復的で再帰的な要素があります

# returns index of wff
def findConnective(wff, indexes):
    if len(wff) == None:
        return -1
    if (len(wff) <= 1):
        return -1                                   # it's an atomic

    for i in range(len(wff)):                       # looping through all chars in wff
        if set([i]) & set(indexes):                     # if operator has already been used
            continue
        else:                                           # if operator has not been usedl
            for j in range(len(connectives)):           # looping through all of the connectives
                if wff[i] == connectives[j]:            # if the wff contains the connective
                    indexes.append(i)                   # keeps track of which operators have already been used
                    return i
# returns what's on left of operator
def createLeft(wff, opIndex):
    if opIndex == -1:
        return wff          # return the atomic
    else:
        return wff[:opIndex]

# returns what's on right of operator
def createRight(wff, opIndex):
    if opIndex == -1:
        return wff          # return the atomic
    else:
        return wff[opIndex+1:]
# returns number of connectives
def numConnectives(wff):
    count = 0
    for c in wff:
        if c == connectives:
            count += 1
    return count
def rec(wff):
    result = []
    ind = []                            # list storing indexes of connectives used
    if len(wff) == 1:
        return wff
    else:
        for i in range(numConnectives(wff)):
            opIndex = findConnective(wff, ind)          # index where the operator is at

            right   = createRight(wff, opIndex)     # right formula
                                                    # the first time it goes through, right is b>c
                                                    # then right is c
            left    = createLeft(wff, opIndex)      # left formula
                                                    # left is a
                                                    # then it is b
            return "(" + rec(left) + wff[opIndex] + rec(right) + ")"
 print(rec("a>b>c"))

私の出力は、それがAND(a>(b>c))であるべきときです。これは、再帰関数内のループが、再帰呼び出しを実行する 2 番目の演算子を決して選択しないために発生します。return ステートメントが for ループの外にある場合、出力は次のようになります。(a>(b>c))((a>b)>c)((a>b)>c)

関数がすべての演算子を通過するようにするにはどうすればよいですか (つまり、関数呼び出しごとにループ全体が実行されます)。

4

1 に答える 1