[英]Loop Never Completes Within Recursive Function
我正在构建一个程序来将括号恢复为句子,使它们成为格式良好的公式(句子逻辑中的WFF)。 例如,
a
是WFF。
a > b
只有1种方法可以修复括号,使其成为WFF,即(a > b)
。
a > b > c
有2种方法可以修复括号以使其成为WFF - ((a > b) > c)
或(a > (b > c))
。
这个算法有一个迭代和递归元素
# 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"))
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))
AND ((a>b)>c)
。 发生这种情况是因为递归函数内部的循环从不选择第二个运算符来执行递归调用。 当return语句在for循环之外时,输出为((a>b)>c)
我如何使它功能遍历所有操作符(也就是每个函数调用执行整个循环)
尽管rec()
for
循环的return
是特定问题,但我认为整体问题是你使问题变得比它需要的更难。 你还在你的处理是不一致的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"))
OUTPUT
% python3 test.py
['(a>(b>c))', '((a>b)>c)']
%
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.