Start learning free

LESSON 87 OF 410 · CONDITIONAL STATEMENTS - CHALLENGES

Recreating the abs() function in Python with O(1) Time Complexity

Practice Read the full explanation

The absolute value function (abs() in many languages) returns the absolute value of a number. This means that it returns a number's positive value. You can think of it as the distance away from zero.

Create your own function that recreates this functionality, using the name and parameter n from the starter code.

Examples:

abs(-12) ➞ 12

abs(-544) ➞ 544

abs(250) ➞ 250

abs(0) ➞ 0

abs(-14) ➞ 14

Note:

Do not use the absolute value function provided by Python (it will defeat the purpose of the challenge)


Hints:


You can make use of < operator with an if statement to check if n is negative.

You can add an else statement to handle the case when n is positive.
STEP 1 OF 3
    Ctrl + Enter to check

    PYTHON · CONDITIONAL STATEMENTS - CHALLENGES

    Recreating Abs in Python, explained

    Understanding the Problem

    The abs() function returns the absolute value of a number, which is the number's positive value. Essentially, it measures the distance of a number from zero on the number line.

    We need to create our own function abs() that mimics this functionality without using Python's built-in abs() function.

    Examples:

    abs(-1.217197940) ➞ 1.21719794
    
    abs(-544.0) ➞ 544
    
    abs(250.3) ➞ 250.3
    
    abs(0) ➞ 0
    
    abs(-0.14) ➞ 0.14
    

    Approach

    To solve this problem, we need to determine if a number is negative. If it is, we return its positive counterpart. If it is already positive or zero, we return the number as is.

    Naive Solution

    A naive solution would involve checking if the number is negative using an if statement and then returning the positive value. This approach is straightforward and efficient for this problem.

    Optimized Solution

    Given the simplicity of the problem, the naive solution is already optimal. The time complexity is O(1) since we are performing a constant-time check and return operation.

    Algorithm

    1. Check if the number is less than zero.
    2. If it is, return the negative of the number (which makes it positive).
    3. If it is not, return the number as is.

    Code Implementation

    def abs(n):
        """
        This function returns the absolute value of a number.
        
        Parameters:
        n (float): The number to find the absolute value of.
        
        Returns:
        float: The absolute value of the number.
        """
        # Check if the number is negative
        if n < 0:
            return -n  # Return the positive counterpart
        else:
            return n  # Return the number as is
    

    Complexity Analysis

    The time complexity of this solution is O(1) because it involves a single comparison and a return statement, both of which are constant-time operations. The space complexity is also O(1) as we are not using any additional data structures.

    Edge Cases

    We need to consider the following edge cases:

    • Zero: abs(0) ➞ 0
    • Negative floating-point numbers: abs(-0.14) ➞ 0.14
    • Large negative numbers: abs(-1000000) ➞ 1000000

    Testing

    To test the solution comprehensively, we should include a variety of test cases:

    # Test cases
    print(abs(-1.217197940))  # ➞ 1.21719794
    print(abs(-544.0))        # ➞ 544
    print(abs(250.3))         # ➞ 250.3
    print(abs(0))             # ➞ 0
    print(abs(-0.14))         # ➞ 0.14
    print(abs(-1000000))      # ➞ 1000000
    

    Thinking and Problem-Solving Tips

    When approaching such problems, it's essential to break down the problem into smaller, manageable parts. Think about the core functionality you need to replicate and consider edge cases early in the process. Practice by solving similar problems and studying different algorithms to improve your problem-solving skills.

    Conclusion

    In this blog post, we discussed how to recreate the abs() function in Python. We explored the problem definition, approach, algorithm, and provided a detailed code implementation. Understanding and solving such problems is crucial for developing strong programming skills.

    Additional Resources

    Keep going with PythonAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free