Transform iterative function into recursive function - python

Locked. There are disputes about this question’s content being resolved at this time. It is not currently accepting new answers or interactions.
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

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

How to debug my Python program, which sums positive numbers based on their evenness

I'm trying to write program that asking the user for positive numbers, if it is an odd number, the software sums all of the odd digits in the number, same for even numbers. After that the software asking non stop for numbers and does the same thing as before, till the user type 0/negative number.
After that the software should print the number with the maximal sum. Sometimes it works and sometimes not.
Code:
def sum_Digits(n):
sum = 0
if n % 2 == 0: #For even numbers
while n>0:
if (n%10)%2 == 0:
sum += n%10
n = n//10
else:
n = n//10
print("sum: " , sum)
return sum
elif n % 2 != 0 : #For odd numbers
while n>0:
if (n%10)%2 != 0:
sum += n%10
n = n//10
else:
n = n//10
print("sum: " , sum)
return sum
def read_Numbers(N):
maX = 0
while N > 0: #while askNum Positive continue summing
suM = sum_Digits(N)
if suM > maX:
maX = N
N = int(input("Please eneter a Natural number: "))
if N <= 0:
return maX
def main():
num = int(input("Please enter a Natural number: ")) #asking the user to enter number
sum_Digits(num)
askNum = int(input("Please eneter a Natural number: "))
maxSum = read_Numbers(askNum)
print("Number with maximal sum: " , maxSum)
main()
Bug:
if user enter a negative number it will continue the loop and print the last entered number
because the program doesn't check for negative numbers
Fix:
I have added a condition if N <= 0:
return maX
this will return the last entered positive number
Bug:
sum_Digits(num)
I have removed this line because it is not needed
because we already call the function sum_Digits in the main function

Calculate and display the sum, the count and the average of the all the entered numbers

print("Enter some number (9999 is for exit): ")
count = 0
sum = 0.0
number = 1
while number != 9999:
number = int(input("-> "))
sum = sum + number
count += 1
if count == 0:
print("Input some numbers")
else:
print("Average of the above numbers are: ", ((sum-9999) / (count-1)))
print("Sum of the above numbers is :", sum-9999)
'''
The average and sum can work properly but just don't know how to display the total entered numbers that the user input?
'''
Just use
print(number)
To print the user input.

Program that separately adds positive and negative inputs and displays the two sums

I'm trying to solve this hw problem:
Write a program that allows a user to keep inputting numbers until the number zero is entered. The program should keep track of two separate sums: The sum of all positive numbers entered and the sum of all negative numbers entered. Once the loop ends the program should display the two sums.
This is what I have so far:
number = int(input("Please enter a number, press 0 to end"))
sum1 = 0
sum2 = 0
while number != 0:
number = int(input("Please enter a number, press 0 to end"))
if number > 0:
sum1 += number
else:
sum2 += number
print("positive sum is", sum1)
print("negative sum is", sum2)
the problem i'm facing is that number needs to be defined in order to start the while loop, and then for the loop to keep asking the question, i need to define number inside the loop too and that messes up the count because the first user input is used just to start the loop and is not counted.
How do i fix this?
You can simply initialize number to something other than 0, so the number isn't asked twice at the start of the program.
sum1 = 0
sum2 = 0
number = -1
while number != 0:
number = int(input("Please enter a number, press 0 to end"))
if number > 0:
sum1 += number
else:
sum2 += number
print("positive sum is", sum1)
print("negative sum is", sum2)
Try doing this. You can delete the sample_input lines and uncomment your original line taking input from stdin:
sample_input = iter([3, -3, 2, -2, 1, -10, 0])
sum1 = 0
sum2 = 0
number = 999
while number != 0:
number = next(sample_input)
#number = int(input("Please enter a number, press 0 to end"))
if number > 0:
sum1 += number
else:
sum2 += number
print("positive sum is", sum1)
print("negative sum is", sum2)
Sample output:
positive sum is 6
negative sum is -15
Use the walrus:
sum1 = 0
sum2 = 0
while number := int(input("Please enter a number, press 0 to end")):
if number > 0:
sum1 += number
else:
sum2 += number
print("positive sum is", sum1)
print("negative sum is", sum2)
And I'd suggest sum_pos and sum_neg as better more meaningful variable names.
Don't use the number test in the while condition. Check for it being 0 after getting the input and break out of the loop.
while True:
number = int(input("Please enter a number, press 0 to end"))
if number == 0:
break
elif number > 0:
sum1 += number
else:
sum2 += number
I prefer this style because it doesn't require you to initialize the variable to a special value. Also, it allows the end value to be something that wouldn't be useful in the rest of the computation.

Sum of n natural numbers using while loop in python [duplicate]

This question already has answers here:
Sum of the integers from 1 to n
(11 answers)
Closed 6 months ago.
The question was tp :write a program to find the sum of n natural numbers using while loop in python.
n = int(input("Enter a number: "))
i = 1
while i<n:
print(i)
i = i + 1
this is what I have done s far...
can not understand what to do next.
n = int(input("enter a number: "))
i = 1
sum = 0
while (i <= n):
sum = sum + i
i = i + 1
print("The sum is: ", sum)
with a while loop the sum of natural numbers up to num
num = 20
sum_of_numbers = 0
while(num > 0):
sum_of_numbers += num
num -= 1
print("The sum is", sum_of_numbers)
You can either follow Alasgar's answer, or you can define a function with the formula for this particular problem.
The code's gonna be something like this:
def natural(n):
sumOfn = (n * (n + 1))/2
terms = int(input("Enter number of terms: "))
natural(terms)
number = int(int(input("Enter the number: "))
if number < 0:
print("Enter a positive number: ")
else:
totalSum = 0
while (number > 0):
totalSum += number
number -= 1
print ("The sum is" , totalSum)
num = int(input('Enter the number : '))
sum = 0
while 0<num:
sum += num
num -= 1
print(f'The sum of the number is {sum}')

Enter n different positive numbers. Calculate the average value of all prime numbers among them. [Python]

I need to do as the title suggests however I have ran into a problem. This is my code so far:
#Input
n = int(input('Enter n: '))
#Prime = 0
p = []
#Loopidty
for i in range(n):
#Ask user to input x
x = int(input('Enter a Number: '))
#Check if prime
if x < 2:
print('The number is not prime.')
else:
for n in range(2, x - 1):
if x % n == 0:
print('The number is not prime.')
break
else:
print('The number is prime.')
p.append(x)
#Answer
Answer = sum(p) / n
print('The answer is: ', Answer)
The issues is when I add the prime numbers to the list it only adds the first number and stops there, how do I combat this?
Many thanks
It's a good idea to break your code into smaller parts. We can create a function to check if a number is prime or not and check that it is correct. After that just add the rest of the code.
import math
def is_prime(x):
"""Check that a number `x``is prime"""
# You only need to go up to sqrt(x)
for n in range(2, int(math.sqrt(x) + 1)):
if x % n == 0:
return False
return True
# xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
sum = 0.0
num_entries = 0 # Number of prime numbers entered by the user
n = int(input('Enter n: '))
for i in range(n):
x = int(input('Enter a Number: '))
if is_prime(x):
sum += x
num_entries += 1
if num_entries == 0:
print("You didn't enter any prime number")
else:
print("The average of the entered prime numbers is ", sum / num_entries)

Categories