This Python program finds the largest even and largest odd numbers in a given list.
Problem Statement:
Given a list of integers, the task is to find and print the largest even number and the largest odd number present in the list.
Python Program to Print Largest Even and Largest Odd Number in a List
def find_largest_even_odd(numbers):
largest_even = float('-inf')
largest_odd = float('-inf')
for num in numbers:
if num % 2 == 0 and num > largest_even:
largest_even = num
elif num % 2 != 0 and num > largest_odd:
largest_odd = num
return largest_even, largest_odd
# Input
num_list = [12, 7, 23, 44, 35, 68, 95, 42, 30]
# Finding largest even and odd numbers
largest_even, largest_odd = find_largest_even_odd(num_list)
# Output
print("Largest Even Number:", largest_even)
print("Largest Odd Number:", largest_odd)
How it Works:
- Define a function
find_largest_even_oddthat takes a list of numbers as input. - Initialize two variables,
largest_evenandlargest_odd, with negative infinity values. - Loop through the numbers in the list.
- If a number is even and greater than the current largest even number, update
largest_even. - If a number is odd and greater than the current largest odd number, update
largest_odd. - Return the values of
largest_evenandlargest_odd. - In the main part of the program, provide the input list of numbers.
- Call the
find_largest_even_oddfunction and store the results inlargest_evenandlargest_odd. - Print the largest even and largest odd numbers.
Input/Output:
Input:
[12, 7, 23, 44, 35, 68, 95, 42, 30]
Output:
Largest Even Number: 68
Largest Odd Number: 95