def get_max(self):
if not self.numbers:
return None
# Logic to find max
current_max = self.numbers[0]
for num in self.numbers:
if num > current_max:
current_max = num
return current_max
```
6. Testing with Input: The input is [1, 4, 8, 6, -2, 5].
* Start with 1.
* 4 > 1 -> max is 4.
* 8 > 4 -> max is 8.
* 6 < 8.
* -2 < 8.
* 5 < 8.
* Result: 8.
7. Final Output Generation: Present the code clearly with comments and show the usage with the provided input.
Here is the solution designed using Object-Oriented Programming (OOP) principles in Python.
Algorithm Design
- Define a Class: Create a class named
MaxFinder that encapsulates the data (the list of integers) and the logic (the method to find the maximum).
- Constructor (
__init__): Initialize the object with the input list.
- Method (
find_max):
- Check if the list is empty to avoid errors.
- Assume the first element is the maximum.
- Iterate through the remaining elements.
- Compare each element with the current maximum. If the element is larger, update the current maximum.
- Return the final maximum value.
Python Implementation
class MaxFinder:
def __init__(self, numbers):
"""
Constructor to initialize the list of integers.
"""
self.numbers = numbers
def find_max(self):
"""
Method to find and return the maximum value in the list.
"""
# Check if the list is empty
if not self.numbers:
return None
# Initialize max_value with the first element
max_value = self.numbers[0]
# Iterate through the list to find the maximum
for num in self.numbers:
if num > max_value:
max_value = num
return max_value
# --- Main Execution ---
# Input data
input_list = [1, 4, 8, 6, -2, 5]
# Instantiate the class
finder = MaxFinder(input_list)
# Call the method and print the result
result = finder.find_max()
print(f"The maximum value is: {result}")
Output
The maximum value is: 8