Цикл никогда не завершается внутри рекурсивной функции - PullRequest
0 голосов
/ 02 июня 2019

Я строю программу для восстановления скобок в предложениях, чтобы превратить их в правильно сформированные формулы (WFF в предложенной логике).Например,

Etc ...

В этом алгоритме есть итеративный и рекурсивный элемент

# 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"))

Мой вывод (a>(b>c))когда это должно быть (a>(b>c)) И ((a>b)>c).Это происходит потому, что цикл внутри рекурсивной функции никогда не выбирает второй оператор для выполнения рекурсивного вызова.Когда оператор return находится вне цикла for, вывод будет ((a>b)>c)

Как мне сделать так, чтобы функция проходила через все операторы (или весь цикл выполняется для каждого вызова функции)

1 Ответ

0 голосов
/ 03 июня 2019

Хотя return в цикле for в rec() является специфической проблемой, я считаю, что общая проблема заключается в том, что вы делаете проблему сложнее, чем нужно.Вы также непоследовательны в обработке connectives, иногда это набор символов range(len(connectives)), иногда один символ wff[i] == connectives[j].Вот мое упрощение вашего кода:

connectives = {'>'}

def findConnectives(wff):
    ''' returns index of wff '''

    if wff is None or len(wff) <= 1:
        yield -1  # it's an atomic
    else:
        for i, character in enumerate(wff):  # looping through all chars in wff
            if character in connectives:  # if the wff contains the connective
                yield i

def createLeft(wff, opIndex):

    ''' returns what's on left of operator '''

    return wff[:opIndex]

def createRight(wff, opIndex):

    ''' returns what's on right of operator '''

    return wff[opIndex + 1:]

def rec(wff):
    if len(wff) == 1:
        return [wff]

    result = []

    for opIndex in findConnectives(wff):
        if opIndex == -1:
            break

        left = createLeft(wff, opIndex) # left formula

        right = createRight(wff, opIndex)  # right formula

        for left_hand in rec(left):
            for right_hand in rec(right):
                result.append("(" + left_hand + wff[opIndex] + right_hand + ")")

    return result

print(rec("a>b>c"))

ВЫХОД

% python3 test.py
['(a>(b>c))', '((a>b)>c)']
%
...