Clamp Implementation
Detailed Clamping Techniques
1. Basic Function Implementation
def custom_clamp(value, min_limit, max_limit):
"""
Clamp a value between minimum and maximum limits
Args:
value (int/float): Input value to be clamped
min_limit (int/float): Minimum allowed value
max_limit (int/float): Maximum allowed value
Returns:
int/float: Clamped value within specified range
"""
return max(min_limit, min(value, max_limit))
## Example usage
print(custom_clamp(15, 0, 10)) ## Output: 10
print(custom_clamp(-5, 0, 10)) ## Output: 0
print(custom_clamp(5, 0, 10)) ## Output: 5
2. Advanced Clamping with Type Checking
def robust_clamp(value, min_limit, max_limit):
"""
Enhanced clamping with type validation
"""
try:
## Ensure consistent type
value = type(min_limit)(value)
if value < min_limit:
return min_limit
elif value > max_limit:
return max_limit
return value
except (TypeError, ValueError):
raise TypeError("Invalid input types for clamping")
## Example with different types
print(robust_clamp(15.5, 0, 10.0)) ## Output: 10.0
Clamping Strategies
graph TD
A[Clamping Strategy] --> B[Basic Clamping]
A --> C[Robust Clamping]
A --> D[Specialized Clamping]
B --> B1[Simple min/max comparison]
C --> C1[Type validation]
C --> C2[Error handling]
D --> D1[Domain-specific constraints]
3. Functional Programming Approach
from functools import partial
def functional_clamp(min_limit, max_limit, value):
"""
Functional programming style clamping
"""
return max(min_limit, min(value, max_limit))
## Create specialized clamp functions
zero_to_hundred = partial(functional_clamp, 0, 100)
## Usage
print(zero_to_hundred(50)) ## Output: 50
print(zero_to_hundred(150)) ## Output: 100
| Method |
Time Complexity |
Memory Overhead |
Flexibility |
| Basic Function |
O(1) |
Low |
Moderate |
| Robust Clamping |
O(1) |
Moderate |
High |
| Functional Approach |
O(1) |
Low |
High |
4. NumPy Vectorized Clamping
import numpy as np
def numpy_vectorized_clamp(array, min_limit, max_limit):
"""
Efficient clamping for numpy arrays
"""
return np.clip(array, min_limit, max_limit)
## Example
data = np.array([1, 5, 10, 15, 20])
clamped_data = numpy_vectorized_clamp(data, 3, 12)
print(clamped_data) ## Output: [3 5 10 12 12]
Best Practices
- Always validate input types
- Choose appropriate clamping method
- Consider performance requirements
- Handle edge cases
Note: LabEx recommends understanding these implementation techniques to write more robust Python code.