【发布时间】:2014-10-02 17:17:46
【问题描述】:
当我运行 testing1 时,一切都很好,但是当我运行 testing/testing3 时,我的函数是无限递归的。我知道为什么,但我不知道如何制作一个处理这种情况的函数。我需要在 frags 开头的辅助函数来检查给定的字符串是否会导致无限递归。有人对如何解决问题有任何想法吗?
testing = ["baa","aaag","gaaaam","mmmmb"]
testing1 = ["good", "odor", "jimmy", "roboj"]
testing3 = {"aab" , "baa"]
def solution(strings):
original = strings[:]
fragmentsList = frags(strings)
RealList = fragmentsList[len(original):]
length = len(RealList)
removeCounter = 0
for x in range(0,length):
for y in range(0,length):
if x!=y:
if RealList[x].find(RealList[y]) != -1 and RealList[y].find(RealList[x]) == -1:# x > y
RealList[y] = " "
removeCounter = removeCounter + 1
for x in range(0,removeCounter):
RealList.remove(" ")
return RealList
def frags(strings):
length = len(strings)
for x in range(0,length):
for y in range(0,length):
if x != y:
if fraghelper(strings[x],strings[y]) != -1:
toAppend = fraghelper(strings[x],strings[y])
for f in range(0,len(toAppend)):
if toAppend[f] not in strings:
strings.append(toAppend[f])
if len(strings) != length:
return frags(strings)
else:
return strings
def fraghelper(string1, string2):
toReturn1 = " "
toReturn2 = " "
for i in reversed(range(len(string1))):
if string2.startswith(string1[-i:]):
toReturn1 = string1[:-i] + string2
for i in reversed(range(len(string2))):
if string1.startswith(string2[-i:]):
toReturn2 = string2[:-i] + string1
if toReturn1 == " " and toReturn2 == " ":
return -1
elif toReturn1 == " ":
return [toReturn2]
elif toReturn2 == " ":
return [toReturn1]
else:
return [toReturn1, toReturn2]
print(testing)
print(solution(testing))
【问题讨论】:
-
一些关于你的代码所做的事情会有所帮助
-
“我知道为什么”你会告诉我们,还是我们必须自己理解你的代码?
-
testing3 = {"aab" , "baa"]是一个突变体dict/list。 frags 是递归的吗?它到底应该做什么? -
不要因为你有答案就抹去你的整个问题。请看stackoverflow.com/help/someone-answers