12345678910111213141516123456781def append(t, x):2 if t.n == t.cap:3 t.cap = max(1, 2 * t.cap)4 new = [None] * t.cap5 for i in range(t.n):6 new[i] = t.a[i]7 t.a = new8 t.a[t.n] = x9 t.n += 1ncapcostbankΦbank
Green blocks: items in the table, one hop per item writtenGrey tiles: the array's slots (its capacity)Gold coins: the 3-coin charge per append, and Φ's two coins per item past halfThe Python append() on the card; each item written into a slot (a copy or the new item) is one unit of work and one hop. When the array is full, a twice-as-big array appears in the other lane and every item hops across, so one append can cost n. Charging 3 coins per append keeps the bank above zero; Φ = 2n − cap counts two coins on each item past the half-way mark.

What one append costs

  1. A dynamic table is an array that can grow. append(x) writes x into the next free slot. When every slot is full, it makes a new array twice as big and copies each item across. Cost rule: each item written into a slot costs 1.

The accounting method

The potential method

What happens

;; step 1/10 · table
cost model: 1 unit per item written into a slot
  1  def append(t, x):             
  2      if t.n == t.cap:          
  3          t.cap = max(1, 2 * t.cap)
  4          new = [None] * t.cap  
  5          for i in range(t.n):  
  6              new[i] = t.a[i]   1 per run
  7          t.a = new             
  8      t.a[t.n] = x              1 per run
  9      t.n += 1                  

n = items stored, cap = slots in the array
the table starts empty: n = 0, cap = 0

Cost model: 1 unit for each item written into a slot, either a copy or the new item. Making the empty new array is not counted; counting it changes the constants, not the O(1) result. The very first append costs 1 and is charged 3, so the bank always holds one coin more than Φ. Its amortised cost under the potential method is 2: 1 + (1 − 0).