Is it possible to transform these three functions into one?
def percentage_liked(ratings): list_liked = [i>=4 for i in ratings] # TODO: Complete the function percentage_liked = list_liked.count(True)/len(list_liked) return percentage_liked def percentage_not_liked(ratings): list_liked = [i<=2 for i in ratings] # TODO: Complete the function percentage_not_liked = list_liked.count(True)/len(list_liked) return percentage_not_liked def neutral_liked(ratings): list_liked = [i==3 for i in ratings] # TODO: Complete the function neutral_liked = list_liked.count(True)/len(list_liked) return neutral_like
Yes, you can consolidate these three functions into one by adding a parameter to specify the condition. Here’s an example:
def calculate_percentage(ratings, condition): list_liked = [condition(i) for i in ratings] # TODO: Complete the function percentage = list_liked.count(True) / len(list_liked) return percentage # Example usage: ratings = [4, 5, 3, 2, 4, 1, 3] percentage_liked = calculate_percentage(ratings, lambda x: x >= 4) percentage_not_liked = calculate_percentage(ratings, lambda x: x <= 2) neutral_liked = calculate_percentage(ratings, lambda x: x == 3) print(f"Percentage Liked: {percentage_liked}") print(f"Percentage Not Liked: {percentage_not_liked}") print(f"Neutral Liked: {neutral_liked}")
In this example, the calculate_percentage function takes a ratings list and a condition function as parameters. The condition function is a lambda function that specifies the condition for each case (liked, not liked, neutral). This way, you can reuse the same function for different conditions.
calculate_percentage
ratings
condition