Data Structures and Algorithms (DSA)  

How to Determine if Three Numbers Are in AP, GP, or HP using Python

Table of Contents

  • Introduction

  • What Are AP, GP, and HP?

  • Why This Matters in Real Life

  • Real-World Scenario: Predicting Sensor Drift in Smart Agriculture

  • Mathematical Conditions

  • Clean, Error-Free Python Implementation

  • Best Practices and Edge Case Handling

  • Conclusion

Introduction

At first glance, arithmetic, geometric, and harmonic progressions (AP, GP, HP) seem like textbook math concepts. But in the age of IoT and predictive analytics, recognizing these patterns in real-time data streams can prevent system failures, optimize resources, and even save crops. This article shows you how to reliably classify any three numbers into one (or none) of these sequences—with production-ready Python code.

What Are AP, GP, and HP?

Arithmetic Progression (AP)

In an arithmetic progression, the difference between each pair of consecutive numbers is always the same.
For example, if you start with one number and keep adding (or subtracting) a fixed amount, you get the next number.

Example: 3, 6, 9 — each term increases by 3.

Geometric Progression (GP)

In a geometric progression, the ratio between each pair of consecutive numbers is constant.
That means each number is obtained by multiplying the previous one by the same factor.

Example: 2, 4, 8 — each term is twice the previous one.

Harmonic Progression (HP)

In a harmonic progression, the reciprocals of the numbers (1 divided by each term) form an arithmetic progression.
In simpler terms, if you take the reciprocals of the numbers, the differences between them are equal.

Example: 1/2, 1/3, 1/4 — the reciprocals (2, 3, 4) form an arithmetic progression.

Why This Matters in Real Life

Pattern recognition in triplets isn’t academic—it’s operational. From financial forecasting to hardware diagnostics, identifying progression types helps systems anticipate the next value or detect anomalies.

Real-World Scenario: Predicting Sensor Drift in Smart Agriculture

In California’s Central Valley, a smart irrigation startup deploys soil moisture sensors across almond orchards. Each sensor reports three consecutive hourly readings to detect calibration drift:

  • Normal: Readings form an AP (steady drying: 40%, 38%, 36%)

  • Failing: Readings form a GP (exponential decay due to battery drop: 50, 25, 12.5)

  • Faulty: Readings form an HP (rare, but indicates pressure-based sensor error)

If none match, the system flags "Anomaly: Possible hardware fault" and dispatches a field technician—before crops are under-watered.

PlantUML Diagram

This real-time classification runs on edge devices with minimal compute, making efficiency and correctness critical.

Mathematical Conditions (Robust Form)

To avoid floating-point errors and division-by-zero:

  • AP: 2 * b == a + c

  • GP: b * b == a * c (and a != 0 if checking ratio)

  • HP: 2 * a * c == b * (a + c) (derived by clearing denominators; avoids 1/x)

We prioritize integer-safe comparisons and explicit zero checks.

Clean, Error-Free Python Implementation

PlantUML Diagram
def classify_progression(a: float, b: float, c: float) -> str:
    """
    Classifies three numbers as AP, GP, HP, or None.
    Handles edge cases: zeros, negatives, and floating-point safety.
    Returns one of: 'AP', 'GP', 'HP', 'None'
    """
    # Handle degenerate case: all zeros
    if a == 0 and b == 0 and c == 0:
        return "AP"  # Also GP, but AP is conventional

    # Check AP: 2b = a + c
    if 2 * b == a + c:
        return "AP"

    # Check GP: b² = a*c (only if middle term allows meaningful ratio)
    if b * b == a * c:
        # Exclude cases like (0, 0, 5) which satisfy b²=ac but aren't true GP
        if a == 0 or b == 0 or c == 0:
            # Only allow GP if all are zero (already handled) or none are zero
            if not (a == 0 and b == 0 and c == 0):
                pass  # Not a valid GP
        else:
            return "GP"

    # Check HP: 2ac = b(a + c), and no zero terms (since 1/0 undefined)
    if a != 0 and b != 0 and c != 0:
        if 2 * a * c == b * (a + c):
            return "HP"

    return "None"


# Simulate real-time sensor analysis
def analyze_sensor_readings(readings):
    result = classify_progression(*readings)
    if result == "None":
        print(f"️  Anomaly in readings {readings}: Possible sensor fault!")
    else:
        print(f" Readings {readings} form a {result}. Behavior is predictable.")


if __name__ == "__main__":
    # Test real-world cases
    test_cases = [
        (40, 38, 36),     # AP: normal drying
        (50, 25, 12.5),   # GP: battery decay
        (1, 0.5, 0.333),  # Approx HP (1, 1/2, 1/3) → but use exact: (6, 3, 2)
        (6, 3, 2),        # Exact HP: reciprocals [1/6, 1/3, 1/2] → AP
        (10, 20, 40),     # GP
        (1, 2, 4),        # None → anomaly
    ]

    for case in test_cases:
        analyze_sensor_readings(case)
22

Best Practices and Edge Case Handling

  • Never use 1/x directly—clear denominators algebraically to avoid ZeroDivisionError.

  • For floating-point data, replace == with abs(x - y) < tolerance.

  • Document assumptions: e.g., “HP requires all non-zero values.”

  • In IoT systems, log unclassified triplets for model retraining.

Conclusion

Classifying triplets into AP, GP, or HP is more than a coding interview question—it’s a lightweight anomaly detection tool for real-world systems. From smart farms to industrial IoT, this tiny function can trigger critical maintenance workflows before failures occur. With clean, defensive code and domain-aware logic, you turn abstract math into actionable intelligence. Next time you see three numbers, ask: What story are they telling? The answer might just save a field of almonds—or your next product launch.