0

I wrote a function to check around 10 000 combinations. It is expected to return some match. For some cases it does.

Problem that sometimes I can print result string inside the function but the function itself returns None object and I cannot use it further

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'

For example this code prints "dearalanhowareyou" at the bottom but returns None

print(result)

"dearalanhowareyou"
paveltr
  • 474
  • 1
  • 8
  • 22
  • 1
    At first guess I’d say you need to write `return find_variants(...)` – N Chauhan Nov 02 '18 at 23:28
  • 1
    You should `return find_variants(pairs_dict, a1, a2, counter = counter)`, otherwise your function ends without an explicit return value, so it will return `None`. – Thierry Lathuille Nov 02 '18 at 23:28

0 Answers0