Python 3D Academyবাংলা

Arrays & Strings in Python

Chapter 34: Arrays & Strings

6 short lessons, with 3D animations, quizzes and coding tasks.

The lessons

  1. Memory as a row of numbered boxes

    An array keeps its items in one unbroken block of memory, side by side, each taking the same space, so the place of item i can be worked out instead of searched for.

  2. Dynamic arrays: how append stays fast

    A dynamic array keeps spare room at the end; when that runs out it moves to a block that is a good deal bigger, so moves happen rarely and their cost, spread over all the appends, stays small.

  3. Insert and delete: the cost of shifting

    Changing an array anywhere but the end means shifting every item after that place by one, so the cost depends on where you change it.

  4. Strings and 2D grids

    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.

  5. Walking a grid: spiral order and turning it round

    Walk a grid in a spiral by keeping four edges (top, bottom, left, right), walking along one side and then moving that edge in; turn a square grid a quarter clockwise by swapping it across its diagonal and then reversing every row.

  6. Cyclic sort: every number in its own seat

    When the values are 1 to n, value x belongs at index x − 1, so keep swapping the number at i into its home until the right number (or a copy of it) is there; then one scan shows which numbers are missing or repeated, in O(n) time and O(1) extra memory.