4 of 6
Count how many times a specific value appears in a 2D grid.
grid = [ [".", "X", "."], ["X", ".", "X"], [".", ".", "X"] ]
Expected output:
Number of X's: 4
grid = [ [".", "X", "."], ["X", ".", "X"], [".", ".", "X"] ] count = ___ for row in grid: for cell in row: if ___: count += ___ print(f"Number of X's: {count}")
Start with count = 0 before the loops.
Check if each cell equals "X": if cell == "X":
Add 1 each time you find an "X": count += 1
Make it work for any value! Ask the user what to search for:
target = input("What to search for? ") # Count how many times target appears
grid = [ [".", "X", "."], ["X", ".", "X"], [".", ".", "X"] ] count = 0 for row in grid: for cell in row: if cell == "X": count += 1 print(f"Number of X's: {count}")
grid = [ [".", "X", "."], ["X", ".", "X"], [".", ".", "X"] ] target = input("What to search for? ") count = 0 for row in grid: for cell in row: if cell == target: count += 1 print(f"Number of '{target}': {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