Today I will solve the next problem. As a reminder, I was giving the solutions to the optional problem sets of Udacity’s ‘Intro To Computer Science’ course. This is a great course for beginners. It helped me a lot. It provides the solution to the problem sets. But it has some optional problem sets too. It doesn’t have the solutions of optional problem sets in it.
Problem (Lesson 7, Quiz 3)
Here is the problem from Lesson 7, Quiz 3:
Problem: The range of a set of values is the maximum value minus the minimum value. Define procedure, set_range, which returns the range of three input values.
Solution
This problem is good problem to solve for a beginner. Probably it is a good idea to break the problem down in smaller parts and solve one small part at a time. That way it’s easy to fix the bugs.
#First write a function bigger to find the bigger number of two numbers
def bigger(a,b):
if a > b:
return a
else:
return b
#This function biggest get the biggest number of any three numbers.
def biggest(a,b,c):
return bigger(a,bigger(b,c))
#Then Write a function smaller that finds the smaller number from any two numbers.
def smaller(a, b):
if a < b:
return a
return b
Now it’s time to calculate the range. Let’s find the biggest number using the biggest function. Then, there will be two small numbers remaining. So, it’s simple to get the smallest of three numbers now. Use the smaller function and put two smaller numbers as input. That should return the smallest number. Now deduct the smallest number from the biggest number.
def set_range(a, b, c):
big = biggest(a, b, c)
if (big == a):
return big – smaller(b, c)
if (big == b):
return big – smaller(a, c)
return big – smaller(a, b)