Programming from zero

Build a service health report from a list of servers

mediumMini scripts — put it all together

Problem statement

This mini script combines four things you already know: a dictionary, a loop, conditions and formatted output.

You have the CPU usage of four services. Classify each one:

  • 90 or more: critical
  • 70 or more (but under 90): warning
  • anything lower: healthy

Then print one line per service and a summary line with the totals.

Common mistake: checking the smaller limit first.

TEXT
Wrong:
if value >= 70: label = "warning"
elif value >= 90: label = "critical"

A value of 95 is already >= 70, so it is labelled warning and the critical branch is never reached. Check the biggest limit first.

Your task: use the CPU usage api 45, cache 72, db 95 and web 30. Print each service as <name>: <value>% <label>, then print Summary: <n> healthy, <n> warning, <n> critical.

Expected output

TEXT
api: 45% healthy
cache: 72% warning
db: 95% critical
web: 30% healthy
Summary: 2 healthy, 1 warning, 1 critical

Approach

Loop over the dictionary, pick a label with if / elif / else, and count each label:

  • Python: for name, value in cpu.items(): gives the key and value together.
  • Java: LinkedHashMap with for (Map.Entry<String, Integer> entry : cpu.entrySet()).
  • C++: std::map with for (const auto& entry : cpu), using entry.first and entry.second.

Note on order: the keys are added in alphabetical order, so Python, Java's LinkedHashMap and C++'s std::map all print the services in the same order.

cpu = {"api": 45, "cache": 72, "db": 95, "web": 30}

healthy = 0
warning = 0
critical = 0

for name, value in cpu.items():
    if value >= 90:
        label = "critical"
        critical += 1
    elif value >= 70:
        label = "warning"
        warning += 1
    else:
        label = "healthy"
        healthy += 1
    print(f"{name}: {value}% {label}")

print(f"Summary: {healthy} healthy, {warning} warning, {critical} critical")