S1Q1 · Classify Temperature¶
⚡ Quick Reference
Function: classify_temperature(temp: str) -> str
Core idea: strip the unit, convert Kelvin to Celsius if needed, then classify.
def classify_temperature(temp: str) -> str:
if temp.endswith("K"):
celsius = float(temp[:-1]) - 273.15
else:
celsius = float(temp[:-1])
if celsius < 15:
return "Cold"
elif celsius <= 30:
return "Moderate"
else:
return "Hot"
Key rules:
- Unit is the last character: "C" or "K"
- temp[:-1] strips the unit to get the numeric value
- Kelvin → Celsius: K - 273.15
- Cold: < 15°C | Moderate: 15°C to 30°C inclusive | Hot: > 30°C
Template Code¶
def classify_temperature(temp: str) -> str:
'''
Classify a temperature given as a string with unit C or K.
Convert Kelvin to Celsius using: °C = K - 273.15
Classification:
"Cold" if celsius < 15
"Moderate" if 15 <= celsius <= 30
"Hot" if celsius > 30
Examples:
>>> classify_temperature("10C")
"Cold"
>>> classify_temperature("20C")
"Moderate"
>>> classify_temperature("290K")
"Moderate"
Args:
temp (str): Temperature string ending with "C" or "K"
Returns:
str: "Cold", "Moderate", or "Hot"
'''
...
Problem Statement¶
Problem
Write a function classify_temperature(temp) that parses a temperature string, converts Kelvin to Celsius if needed, and returns the classification.
Examples:
"10C"
"Cold"
"290K"
"Moderate"
"310K"
"Hot"
"-5C"
"Cold"
Tracing all examples¶
| Input | Unit | Value | Celsius | Classification |
|---|---|---|---|---|
"10C" |
C | 10 | 10.0 | 10 < 15 → Cold |
"20C" |
C | 20 | 20.0 | 15 ≤ 20 ≤ 30 → Moderate |
"35C" |
C | 35 | 35.0 | 35 > 30 → Hot |
"290K" |
K | 290 | 16.85 | 15 ≤ 16.85 ≤ 30 → Moderate |
"310K" |
K | 310 | 36.85 | 36.85 > 30 → Hot |
"-5C" |
C | -5 | -5.0 | -5 < 15 → Cold |
Solution approaches¶
Key takeaways¶
temp[:-1] strips the unit
The last character is always the unit ('C' or 'K'). Slicing with [:-1] removes it, leaving the numeric string ready for float(). Works for negative values like "-5C" too.
K - 273.15 converts to Celsius
0°C = 273.15 K. Always subtract 273.15 when converting from Kelvin. Only apply conversion for 'K' - leave Celsius values unchanged.
Boundary values: 15 and 30 are Moderate
The ranges are: Cold is strictly less than 15; Moderate is 15 to 30 inclusive; Hot is strictly greater than 30. Use < 15 then <= 30 to get this right.