A like total that grows with every call

Code review · Medium · §11.5, §11.7 [Pair coding with AI] Asking for class design

You asked an AI to write a class that totals the likes in a list of posts. This is the code it gave you. It runs without errors, and the 30 on the first line is right, but the second line prints 42 when it should print 12. Nothing needs to be remembered between calls, so delete the class and rewrite it as a function total_likes(posts). Change the two lines at the bottom to call this function too. Grading also calls the function with other lists.

Code to fix

class LikeSummary:
    def __init__(self):
        self.total = 0

    def total_likes(self, posts):
        for post in posts:
            self.total += post["likes"]
        return self.total

summary = LikeSummary()
print(summary.total_likes([{"likes": 10}, {"likes": 20}]))
print(summary.total_likes([{"likes": 12}]))

Solve this problem in your browser

Python runs in your browser and checks your answer right away. Hints and the answer are on the problem page.