4 of 6
In a game inventory, you might have a list like ["sword", "potion", "shield", "potion"]. Write a function that counts how many times a specific item appears.
Write a function count_item(inventory, item) that:
def count_item(inventory, item): # Your code here pass # Test your function: backpack = ["sword", "potion", "shield", "potion", "Sword"] print(count_item(backpack, "potion")) # Should print: 2 print(count_item(backpack, "sword")) # Should print: 2 print(count_item(backpack, "bow")) # Should print: 0
Use a counter variable. Loop through the list and add 1 each time you find a match.
To compare case-insensitively, convert both strings to lowercase with .lower():
if thing.lower() == item.lower():
def count_item(inventory, item): count = 0 for thing in inventory: if thing.lower() == item.lower(): count += 1 return count
β Standard library: heapq, collections, itertools, math, random, functools, datetime, bisect
β Functions, classes, recursion, print()
β No file system, subprocess, OS access, or network requests
β No pip install (all supported modules are pre-loaded)
β±οΈ 5 second execution time limit