Refactor Legacy Data Processor for Improved Readability and Performance
You are provided with a legacy Python function that processes a list of user records to generate a summary report. Although the function works correctly, it is difficult to read, contains redundant computations, and has inefficient constructs. Your task is to refactor this code to improve readability, maintain the same behavior, and optimize performance while adhering to Python best practices.
Challenge prompt
Below is a legacy Python function named process_user_data which takes a list of user dictionaries and returns a summary dictionary with average age, count of active users, and a list of usernames sorted alphabetically. Refactor this function to improve code clarity and efficiency without changing its behavior. Pay particular attention to redundant code blocks, repeated calculations, and code structure. Ensure your version is idiomatic Python and easy to understand.
Guidance
- • Identify and eliminate repeated computations or redundant loops.
- • Consider using built-in Python functions and comprehensions for clarity and performance.
- • Maintain clear naming and structure for variable and function usage.
Hints
- • Avoid recalculating the length of lists multiple times; store results when possible.
- • Use generator expressions or list comprehensions for filtering and mapping data.
- • Utilize built-in functions like sum(), sorted(), and len() efficiently.
Starter code
def process_user_data(users):
total_age = 0
count_active = 0
usernames = []
for i in range(len(users)):
if users[i]['active'] == True:
count_active += 1
total_age += users[i]['age']
for i in range(len(users)):
usernames.append(users[i]['username'])
average_age = total_age / len(users)
usernames.sort()
result = {
'average_age': average_age,
'active_user_count': count_active,
'sorted_usernames': usernames
}
return resultExpected output
{ 'average_age': 29.6, 'active_user_count': 3, 'sorted_usernames': ['alice', 'bob', 'charlie', 'diana', 'eve'] } # For input example users: [ # {'username': 'alice', 'age': 31, 'active': True}, # {'username': 'bob', 'age': 22, 'active': False}, # {'username': 'charlie', 'age': 29, 'active': True}, # {'username': 'diana', 'age': 35, 'active': True}, # {'username': 'eve', 'age': 22, 'active': False} # ]
Core concepts
Challenge a Friend
Send this duel to someone else and see if they can solve it.