Course Content
Python Indentation, Comments and Variables
0/2
Object Oriented Programming in Python
0/1
Exception Handling in Python
0/1
Sending emails with Python
0/1
Unit test in python programming
0/1
Python programming (zero to advance!!!)
About Lesson

Min-maxing

Define a function named largest_difference that takes a list of numbers as its only parameter.

Your function should compute and return the difference between the largest and smallest number in the list.

For example, the call largest_difference([1, 2, 3]) should return 2 because 3 - 1 is 2.

You may assume that no numbers are smaller or larger than -100 and 100.

 

==== SOLUTION ====

You can implement the `largest_difference` function in Python by finding the maximum and minimum values in the list and then computing their difference.

Here’s how you can do it:

“`python
def largest_difference(numbers):
        # Find the maximum and minimum values in the list
        max_num = max(numbers)
        min_num = min(numbers)
       # Compute and return the difference
       return max_num – min_num

# Test the function
print(largest_difference([1, 2, 3])) # Output: 2
“`

Explanation:

1. `def largest_difference(numbers):`: This line defines a function named `largest_difference` that takes a single parameter `numbers`, which is a list of numbers.

2. `max_num = max(numbers)`: This line finds the maximum value in the list `numbers` using the `max()` function.

3. `min_num = min(numbers)`: Similarly, this line finds the minimum value in the list `numbers` using the `min()` function.

4. `return max_num – min_num`: This line computes the difference between the maximum and minimum values and returns it.

So, when you call `largest_difference([1, 2, 3])`, it returns `2` because the difference between the largest number `3` and the smallest number `1` is `2`.

 

Join the conversation