递归函数打印结果,但返回无

时间:2018-11-02 23:24:27

标签: python algorithm recursion tail-recursion

我编写了一个函数来检查大约10000种组合。预计将返回一些匹配项。在某些情况下确实如此。

问题:有时我可以在函数内部打印结果字符串,但函数本身返回None对象,我无法进一步使用它

def find_variants(pairs_dict, a1, a2, counter = 1):
    variants = pairs_dict['variants']
    new_results = []
    for key_start in pairs_dict['start_pairs']:
        for key_end in pairs_dict['end_pairs']:
            if key_start != key_end:
                candidates = [(el1, el2) for el1, el2 in zip(a1, a2) if (el1, el2) != key_start \
                              and (el1, el2) != key_end]
                new_variants = []
                for c in candidates:
                    for variant in variants[key_start]:
                        option = variant + [c]

                        current_score = num_common_letters(''.join(el[0] for el in option),\
                                                                       ''.join(el[1] for el in option))
                        base_score = num_common_letters(''.join(el[0] for el in variant),\
                                                                       ''.join(el[1] for el in variant))

                        if current_score > base_score:
                            new_variants.append(option)
                            if ''.join(el[0] for el in option) == ''.join(el[1] for el in option):
                                return ''.join(el[0] for el in option)
                            elif ''.join(el[0] for el in option + [key_end]) == ''.join(el[1] for el in option + [key_end]):
                                new_results.append(''.join(el[0] for el in option + [key_end]))
                        else:
                            new_variants.append(variant)
        pairs_dict['variants'][key_start] = new_variants
    pairs_dict['results'].append(new_results)

    counter += 1
    if counter <= len(a1):
        find_variants(pairs_dict, a1, a2, counter = counter)
    else:

        matches = list(filter(lambda x: len(x) > 0, flatten(pairs_dict['results'])))
        if len(matches) > 0:
            matches = sorted(matches, key=lambda x: (len(x), x[0]))
            result = matches[0]
            print(result)
            return result
        else:
            return 'IMPOSSIBLE'

例如,此代码在底部显示“ dearalanhowareyou”,但返回None

print(result)

"dearalanhowareyou"

0 个答案:

没有答案