pythonintermediate10 minutes
Refactor a Function to Calculate Average Temperatures with Clean Code Practices
Improve the readability, efficiency, and maintainability of a messy Python function that calculates the average temperature from a list of daily readings.
Challenge prompt
You are given a function that calculates the average temperature from a list of daily temperature readings. The function works correctly but is poorly structured, has redundant code, and uses unclear variable names. Refactor the function to improve readability, remove unnecessary steps, and use Pythonic best practices without changing its output behavior.
Guidance
- • Rename variables to meaningful names that reflect their purpose.
- • Remove redundant calculations or variables that do not contribute to the final result.
- • Use Python built-in functions and idiomatic constructs where appropriate.
Hints
- • Consider using the built-in sum() and len() functions instead of manually accumulating values.
- • Avoid unnecessary initialization of variables that are reassigned later.
- • List comprehensions or generator expressions can simplify iteration.
Starter code
def average_temperature(data):
total = 0
count = 0
for i in range(0, len(data)):
temp = data[i]
total += temp
count = count + 1
avg = total / count
return avgExpected output
If called with average_temperature([70, 72, 68, 71, 69]), the function should return 70.0 without any change in output after refactoring.
Core concepts
code refactoringPython built-inscode readabilityvariable naming
Challenge a Friend
Send this duel to someone else and see if they can solve it.