0

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!

M Z
  • 4,571
  • 2
  • 13
  • 27
Horstus
  • 13
  • 3

1 Answers1

0

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]
Sahadat Hossain
  • 3,583
  • 2
  • 12
  • 19