Python 3D Academyবাংলা

Strings and 2D grids

🌍 In real life. A shop's signboard is painted letter by letter: you can read any letter at a glance, but to fix one letter the painter repaints a whole new board. And in an exam hall the seat plan is a grid: "row 2, bench 3" takes you straight to one seat, first to the row, then along it.

Strings and grids are both arrays underneath. This lesson shows what that means for their costs, and the two traps that catch almost everyone.

The idea in one sentence: a string is an array of characters that can't be changed, and a grid is a list of rows, so both reach any item in O(1) but pay O(n) for every copy or rebuild.

Its words:

  • character: one letter, digit, space or symbol of a string
  • immutable: can't be changed after it is made; a string "change" builds a new string
  • "".join(parts): glues a list of strings together in one pass
  • row and column: grid[r][c] is row r first, then column c inside that row

A string is an array of characters. text[i] and len(text) are O(1), worked out just like a list. But a string is immutable: text[0] = "d" raises TypeError. Every "change" (text.upper(), text + "!", text.replace(…)) builds a new string, copying every character: O(n).

The trap: building a string with += in a loop. Each result += part may copy everything built so far, so k parts can cost 1 + 2 + … + k copies: O(k²). (CPython can sometimes grow the string in place, but don't rely on it.) The fix is to collect the parts in a list, where append is O(1), and glue them once at the end with "".join(parts): one pass, O(n).

A 2D grid is a list of rows. grid[r] is row r (a list), and grid[r][c] is the item in column c of that row: two O(1) steps. Visiting every cell takes rows × columns steps, O(r × c), done row by row with a loop inside a loop. Watch the loop walk the exam hall, row by row:

parts = []
for word in ["Python", "is", "fun"]:
    parts.append(word.upper())        # O(1) each
print("-".join(parts))                # glue once: O(n)

hall = [["A1", "A2", "A3"], ["B1", "B2", "B3"]]
print(hall[1][2], len(hall), len(hall[0]))

bad = [[0] * 3] * 2                   # two references to ONE row
bad[0][0] = 7
print(bad)
good = [[0] * 3 for _ in range(2)]    # a new row each time
good[0][0] = 7
print(good)
[[0] * 3] * 2 copies the reference to the row, not the row: changing one "row" changes both. Make each row with a comprehension.

Mistakes and edge cases. grid[c][r] instead of grid[r][c] reads the wrong cell, or raises IndexError when the grid isn't square: row first, then column. An empty grid [] has no grid[0], so check before asking for the number of columns.

Quiz

  1. What does this print?

    text = "DHAKA"
    print(text[1], len(text))
  2. What happens when this runs: text = "dhaka" then text[0] = "D"?

    • TypeError: strings can't be changed in place
    • text becomes "Dhaka"
    • A new string is made and stored in text
  3. What does this print?

    grid = [[1, 2, 3], [4, 5, 6]]
    print(grid[1][0], len(grid), len(grid[0]))
  4. What does this print?

    grid = [[0] * 2] * 2
    grid[0][0] = 7
    print(grid)
  5. You build one long message from 10,000 small pieces. Which way is O(n)?

    • Append the pieces to a list, then "".join(parts) once
    • message += piece for every piece
    • message = piece + message for every piece
  6. This should put an X on the middle seat only, but every row shows .X. Which line is wrong?

    hall = [["."] * 3] * 3
    hall[1][1] = "X"
    for row in hall:
        print("".join(row))

Coding tasks

  1. Write compress(text): replace each run of the same letter with the letter and the run's length, so "aaabcc" gives "a3b1c2". Collect the parts in a list and join them once.

  2. Write make_grid(rows, cols, fill): a grid of rows rows and cols columns, every cell fill, where each row is its own list.

  3. Write transpose(grid): a new grid of lists whose rows are the columns of grid, so [[1, 2, 3], [4, 5, 6]] gives [[1, 4], [2, 5], [3, 6]]. An empty grid gives [].