简体   繁体   中英

Can not return a list from a recursive function

I'm having an issue returning the result of a recursive function with Python.

My function needs to return a list of pairs of possible comparisons between integers in a range of max list_upper_range .

It's important that two ints are paired only once each pair.

The function behaves as expected until I print the result, having returned the result to where the function was called.

def generate_comparisons_list(list_upper_range, iter_start, list_of_cases):
    if iter_start == list_upper_range:
        #print(list_of_cases) here verified condition was met
        return list_of_cases

    for i in range(iter_start+1, list_upper_range):
        this_case = [iter_start, i]
        list_of_cases.append(this_case)

    iter_start += 1
    generate_comparisons_list(list_upper_range, iter_start, list_of_cases)

list_of_cases_a_and_b = generate_comparisons_list(list_upper_range=6, iter_start=1, list_of_cases=[])

print(list_of_cases_a_and_b) #returns None

Result should be returned as

[[1, 2], [1, 3], [1, 4], [1, 5], [2, 3], [2, 4], [2, 5], [3, 4], [3, 5], [4, 5]]

Have I misunderstood the way Python handles lists in recursive functions?

python functions don't automatically return the last statement (the way ruby does), you have to do a

return generate_comparisons_list(list_upper_range, iter_start, list_of_cases)

at the end of your function.

Have a look here to see it working.

Your function generate_comparisons_list() is intended to return a list, but in the recursive call, the return value is discarded. Your need to return the result

return generate_comparisons_list(list_upper_range, iter_start, list_of_cases)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM