3 of 6
Find the largest number in a 2D grid.
grid = [ [3, 7, 2], [9, 1, 5], [4, 8, 6] ]
Expected output:
The largest number is 9
grid = [ [3, 7, 2], [9, 1, 5], [4, 8, 6] ] largest = ___ for row in grid: for num in row: if ___: largest = ___ print(f"The largest number is {largest}")
Start with the first element: largest = grid[0][0]. This way you're comparing against an actual value from the grid.
Update largest whenever you find a number bigger than the current largest: if num > largest:
largest = grid[0][0] for row in grid: for num in row: if num > largest: largest = num
Also print where the largest number is (its row and column):
The largest number is 9 at row 1, col 0
You'll need to use range(len(...)) so you know the row and column indices. Save them when you find a new largest.
grid = [ [3, 7, 2], [9, 1, 5], [4, 8, 6] ] largest = grid[0][0] for row in grid: for num in row: if num > largest: largest = num print(f"The largest number is {largest}")
grid = [ [3, 7, 2], [9, 1, 5], [4, 8, 6] ] largest = grid[0][0] largest_r = 0 largest_c = 0 for r in range(len(grid)): for c in range(len(grid[r])): if grid[r][c] > largest: largest = grid[r][c] largest_r = r largest_c = c print(f"The largest number is {largest} at row {largest_r}, col {largest_c}")
β 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