Here’s a Python function that calculates the difference between the largest even number and the smallest odd number in a list of integers:
def find_difference(nums):
# Filter even and odd numbers
even_numbers = [num for num in nums if num % 2 == 0]
odd_numbers = [num for num in nums if num % 2 != 0]
def find_difference(nums):
# Filter even and odd numbers
even_numbers = [num for num in nums if num % 2 == 0]
odd_numbers = [num for num in nums if num % 2 != 0]
# Check if there are both even and odd numbers in the list
if not even_numbers or not odd_numbers:
return "List must contain both even and odd numbers"
# Find the largest even and smallest odd numbers
largest_even = max(even_numbers)
smallest_odd = min(odd_numbers)
# Calculate the difference
difference = largest_even - smallest_odd
return difference
Explanation
- The function
find_difference
takes a list of integersnums
. - It separates even and odd numbers using list comprehensions.
- If there are no even or odd numbers, it returns a message indicating that both types are needed.
- It finds the largest even number and smallest odd number.
- Finally, it calculates and returns the difference between them.
Example Usage
numbers = [3, 8, 5, 12, 7, 2]
result = find_difference(numbers)
print(result) # Output: 7 (12 - 5)
This function assumes that the list contains at least one even and one odd number for the calculation.
1 thought on “Write a function to find the difference between the largest even number and smallest odd number in a list of integers.”