Transform iterative function into recursive function

Question:

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

Asked By: nope

||

Answers:

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

Answered By: blhsing
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.