Home > database >  Transform iterative function into recursive function
Transform iterative function into recursive function

Time:08-26

def solowayAverage():
    number = int(input("Enter a number: "))
    sum = 0
    count = 0
    while number != 99999:
        if (number >= 0):
            sum  = number
            count  = 1
        number = int(input("Enter a number: "))
    print("The average is: ", sum / count)
#iterative code

solowayAverage()

def solowayaveragerec(n, sum, count):
    if n !=99999 and n>0:
        sum  = n
        count  = 1
    else:
    return  solowayaveragerec(n, sum, count)

number = int(input("Give me a number: "))
solowayaveragerec(number, 0, 0)
#recursive code non completed

I would need help to make the recursive code work. The problem is that I don't know where to insert the call for the function in the recursive part

CodePudding user response:

You should make the recursive call with the new number added to the sum and the count added with 1:

def solowayaveragerec(sum=0, count=0):
    number = int(input("Enter a number: "))
    if number == 99999:
        print("The average is: ", sum / count)
    else:
        solowayaveragerec(sum   number, count   1)

solowayaveragerec()

Demo: https://replit.com/@blhsing/PrimeSadClosedsource

  • Related