坚持递归Python

时间:2015-11-30 20:33:23

标签: python recursion

我的基本递归函数是这样的:

input_string将采用这种格式= [[cow pig donkey],'pig dog']

for line in Body850:
    for x in line.split('","'):
        if x in KEY:
             END += KEY[x]
        else
             pass # do something here in case x is not in KEY
    print line

[牛猪驴],[猪],[狗]

keep_track = []
def recursion(input_string, finding_name):
    list_names = list format

即[猪]

    for item in list_names:
        if item is A SINGLE WORLD:

即[牛驴]

            if name is finding_name:
                keep_track append name
        else name is A LIST WITH MULTIPLE WORDS:

[牛],[猪],[驴]

这是我陷入困境的地方。因为我在最后有一个return语句

            recursion([cow pig donkey], finding_name)

如果调用我的递归,我的函数会多次返回。我不知道如何修复我的功能,所以我只返回一次。

没有评论的功能

    return keep_track

1 个答案:

答案 0 :(得分:2)

你的问题很乱,所以你很难理解你想要问的问题。一个小时后,它仍然不清楚。我将尽最大努力尝试回答看似问题的事情。

似乎你已经获得了任意深度嵌套的字符串列表。类似的东西:

in_lst = ['horse', 'cow', 'dog', ['pig', 'pig', 'horse'], 'cat', 'sheep']

并且您希望最终得到一个包含特定字符串

的所有匹配项的列表
foo(in_lst, "pig") == ["pig", "pig"]
foo(in_lst, "horse") == ["horse", "horse"]
foo(in_lst, "dog") == ["dog"]

最简单的方法是将列表展平,然后过滤(而不是直接递归)。

# Python3.3+
def flatten(lst):
    for el in lst:
        try:
            yield from flatten(el)
        except TypeError:
            yield el

# Python3, before 3.3
def flatten(lst):
    accum = []
    for el in lst:
        if hasattr(el, "__iter__") and not isinstance(el, str):
            accum.extend(flatten(el))
        else:
            accum.append(el)
    return accum

# Python2
def flatten(lst): 
    # same as Python3 before 3.3, except replace
    ...
        if hasattr(el, "__iter__") and not isinstance(el, str):
    # with
    ...
        if hasattr(el, "__iter__") and not isinstance(el, basestring):

def find_names(haystack, needle):
    return filter(lambda el: el==needle, flatten(haystack))
    # or return [el for el in flatten(haystack) if el == needle]

如果由于某种原因必须直接递归(提示:不要),那么尝试使用扁平化时使用的相同方法:

def find_names(haystack, needle):
    accum = []
    for el in lst:
        if hasattr(el, "__iter__") and not isinstance(el, str):
            accum.extend(find_names(el, needle))
        elif el == needle:
            accum.append(el)
    return accum

虽然可以说计算起来可能更容易。

def find_names(haystack, needle):
    return [needle] * sum(1 for el in flatten(haystack) if el==needle)