PYTHON QUESTION 3: (2 points) Ask the user to enter two integers to form a range
ID: 645289 • Letter: P
Question
PYTHON
QUESTION 3: (2 points) Ask the user to enter two integers to form a range. Similar to range function the first number (included) ?s where the range starts and second number (excluded) is where ?t ends. a) Write a function that returns the sum of all the integers between these numbers using iteration (for loop). (1 point) b) Write a function that returns the sum of all the integers between these numbers using recursion. (1 point) Call these functions back to back on your main program. Print the results of two calls with explanation. E.g. Iteration sum of range (x, y) is $$$, Recursion sum of range(x, y) ?s $$$.Explanation / Answer
def digitSum(num):
total = 0
for digit in str(num):
total += int(digit)
return total
def sumOfSums(n1, n2):
total = 0
for num in range(n1, n2+1):
total += digitSum(num)
return total
def recofSums(n1,n2)
if(n2==n1)
return 0
return n1+recofSums(0,n2-1)
def main()
n1 = input("Enter the first number in range: ")
n2 = input("Enter the last number in range: ")
print "Iteration result", sumOfSums(int(n1), int(n2))
print "Recursive result", recofSums(int(n1), int(n2))
Explanation:In main function we are taking range for the integers we need to add.In sub functions initially we are adding integers based on given range by stroing values using an array and later adding them.For recursive function we are checking condition like when start range is equal to end range and we are retuning the sum of value.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.