Implementation of Lambda Function within a Function

Implementation of Lambda Function within a Function

Programs for Lambda Functions within Functions

Program 1: Function with a Lambda Expression for Customizable Mathematical Operations

def math_operation(x, y, operation):
    """Perform a mathematical operation on two numbers using a lambda function."""
    return operation(x, y)

# Example usage
add = lambda x, y: x + y
subtract = lambda x, y: x - y

print("Addition Result:", math_operation(5, 3, add))
print("Subtraction Result:", math_operation(5, 3, subtract))

Expected Output:

Addition Result: 8
Subtraction Result: 2

Program 2: Function to Apply a Discount Using a Lambda Expression

def apply_discount(price, discount):
    """Applies a discount using a lambda expression."""
    calculate_discount = lambda p, d: p * (1 - d / 100)
    return calculate_discount(price, discount)

# Example usage
print("Price after 10% discount:", apply_discount(200, 10))
print("Price after 20% discount:", apply_discount(300, 20))

Expected Output:

Price after 10% discount: 180.0
Price after 20% discount: 240.0

Program 3: Function to Return a Customized Greeting Using a Lambda

def personalized_greeting(name, greeting):
    """Generates a personalized greeting."""
    return greeting(name)

# Lambda function for the greeting
hello = lambda name: f"Hello, {name}!"
good_morning = lambda name: f"Good morning, {name}!"

# Example usage
print(personalized_greeting("Alice", hello))
print(personalized_greeting("Bob", good_morning))

Expected Output:

Hello, Alice!
Good morning, Bob!

Program 4: Function That Generates Power Functions Using Lambda

def power_function(n):
    """Returns a lambda function to raise a number to the power of n."""
    return lambda x: x ** n

# Example usage
square = power_function(2)
cube = power_function(3)

print("Square of 4:", square(4))
print("Cube of 3:", cube(3))

Expected Output:

Square of 4: 16
Cube of 3: 27

Program 5: Lambda Function for Conditional Text Transformation

def text_transformer(text, transform_type):
    """Applies a text transformation based on the provided lambda function."""
    transformations = {
        "uppercase": lambda x: x.upper(),
        "lowercase": lambda x: x.lower(),
        "titlecase": lambda x: x.title()
    }
    return transformations[transform_type](text)

# Example usage
print(text_transformer("Hello World", "uppercase"))
print(text_transformer("Hello World", "lowercase"))
print(text_transformer("hello world", "titlecase"))

Expected Output:

HELLO WORLD
hello world
Hello World

These examples demonstrate how lambda functions can be incorporated within other functions for dynamic and customized behavior. Let me know if you’d like to proceed with the next topic!

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top