Home > other >  Recursively implement the function halves that takes two positive integers a and b, and returns a li
Recursively implement the function halves that takes two positive integers a and b, and returns a li

Time:11-15

Recursively implement the function halves that takes two positive integers a and b, and returns a list containing the value a (converted to type float) and all successive halves of a that are greater than b. I tried like this but it's returning an empty list and I don't understand what's going on:

def metades(a, b):
    if a < b: return []
    if a > b:

        lst = []
        a = float(a/2) 
        lst.append(a)

        return lst and metades(a,b)

print(metades(100,3))

Should return:

[100.0, 50.0, 25.0, 12.5, 6.25, 3.125]

Return:

[]

CodePudding user response:

To handle a list in a recursive function, you must take it into the function's arguments:

def metades(a, b, res = None):

    res = res or []

    if a <= b: return res
    if a > b:
        res.append(a)  # put first append and then division to retrieve also first value of 'a'
        a = float(a / 2)

        return metades(a, b, res)

print(metades(100,2))

output will be:

[100, 50.0, 25.0, 12.5, 6.25, 3.125]

CodePudding user response:

# your code goes here
def metades(a, b):
        result = []
        if a >= b:
            result.append(float(a))
            result.extend(metades(a/2, b))
        return result
    
print(metades(100,3))

output

[100, 50.0, 25.0, 12.5, 6.25, 3.125]
  • Related