Type Errors: Text That Looks Like a Number
~9 mindebugging
total_readings is meant to add up a list of numbers that arrived as strings. It currently returns "101520" instead of 45, because it is concatenating text rather than adding numbers.
Fix it so it returns the numeric total. Values may be decimals like "2.5", so convert with .
Examples
Three numeric strings add up instead of concatenating
- Input
- total_readings(["10", "15", "20"])
- Output
- 45
Decimal strings are handled, so float not int
- Input
- total_readings(["2.5", "0.5"])
- Output
- 3
An empty list totals 0
- Input
- total_readings([])
- Output
- 0
Hints
Hint 1
Walk the input once and accumulate as you go.
Hint 2
Watch for this: still concatenating.
Requirements
readings: a list of strings, each one a number, e.g. ["10", "15"]Return the numeric total.
Constraints
Standard library only, no imports required
Time limit: 200 ms, Memory: 64 MB
Where this shows up
~9 min
••••••
3 employers weight this skill
2 frontier labs, 1 AI product company. Top match scores 80.
Python
def total_readings(readings):
"""
Add up sensor readings that arrived as strings.
This currently glues the text together instead of adding. Fix it.
Args:
readings: a list of strings, each one a number, e.g. ["10", "15"]
Returns:
The numeric total.
"""
total = ""
for reading in readings:
total = total + reading
return total