Python recursive function returns None instead of value

Question:

I am just experimenting a little bit with Python and recursive functions.

For now, I wanted to write a function, which splits up a number into 4 pieces until it is smaller than 4.

So, for instance, I feed the function 20, it should then return

[1.25,1.25,1.25,1.25,1.25,1.25,1.25,1.25,1.25,1.25,1.25,1.25,1.25,1.25,1.25,1.25]

I get that result if I print the outcome before the return statement, but cannot get that result if I return the variable which contains these values.

def break_up_number_into_fours(input):
    flag = 0
    input_list = []
    full_result = []
    if isinstance(input, list):
        input_list.extend(input)
    else:
        input_list.append(input)

    for item in input_list:
        if item > 4:
            result = [item/4]*4
            full_result.extend(result)
            flag = 1
        else:
            full_result.append(item)

    if flag == 1:

        break_up_number_into_fours(full_result)
    else:
        print(full_result)
        return full_result

test = break_up_number_into_fours(20)

print(test)

What could be wrong in the code?

Much obliged!

Asked By: Horstus

||

Answers:

You did not return any value from your recursive call break_up_number_into_fours(full_result) , you need to do it like:

def break_up_number_into_fours(input):
    flag = 0
    input_list = []
    full_result = []
    if isinstance(input, list):
        input_list.extend(input)
    else:
        input_list.append(input)

    for item in input_list:
        if item > 4:
            result = [item/4]*4
            full_result.extend(result)
            flag = 1
        else:
            full_result.append(item)

    if flag == 1:

        return break_up_number_into_fours(full_result) // here you need to return the value in respective recursive call
    else:
        print(full_result)
        return full_result

test = break_up_number_into_fours(20)

print(test)

Output:

[1.25, 1.25, 1.25, 1.25, 1.25, 1.25, 1.25, 1.25, 1.25, 1.25, 1.25, 1.25, 1.25, 1.25, 1.25, 1.25]

[1.25, 1.25, 1.25, 1.25, 1.25, 1.25, 1.25, 1.25, 1.25, 1.25, 1.25, 1.25, 1.25, 1.25, 1.25, 1.25]
Answered By: Sahadat Hossain
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.