Paul's Python CoursePPC

Project 6 of 15, for Neil

Linked List

A linked list from scratch. The kart track chalked an arrow on every crate of its old kart, each one pointing at the next: build it from two classes, add crates, take them off, and turn the round round.

About 70 minutes, in 10 steps.

Sign up free to open itLog in

Act 4 needs a free account, so your work is saved as you go. Act 1 is open to everyone.

The brief

  • NeilThe kart track's crates came with chalk on them, and each one says which crate comes next.
  • NeilStart at the door and follow the chalk and you get axle, brakes, chassis and drive chain, a whole kart in order.
  • NeilI want to put one in, take one out and go round backwards, all without lifting a single crate.
  • PaulThen each crate only needs to know which crate comes after it, and you can build the rest from that.

In chalk_round.py, two classes.

Crate(part) is one crate on the round: part is what's in it, and next is the next Crate, or None at the end of the round.

Round() is the round of crates, which starts empty. head is its first crate, or None.

  1. append(part) puts a new crate at the end of the round.
  2. parts() returns a list of the parts, in round order.
  3. len(round) is how many crates are on it.
  4. insert_after(existing, part) puts a new crate straight after the first crate holding existing, and raises ValueError if there isn't one.
  5. remove(part) takes the first crate holding part off the round, and raises ValueError if there isn't one.
  6. reverse() turns the round round in place, by changing where the crates point. No new crates.

The crates are linked to each other, not kept in a Python list.

What it prints
Round: ['axle', 'brakes', 'chassis', 'drive-chain']
After the brakes, a fuel tank: ['axle', 'brakes', 'fuel-tank', 'chassis', 'drive-chain']
Neil took the axle: ['brakes', 'fuel-tank', 'chassis', 'drive-chain']
From the far end: ['drive-chain', 'chassis', 'fuel-tank', 'brakes']
4 crates

What you learn

What's in it

  1. Each crate knows the next
  2. Follow the chalk
  3. Changing two arrows
  4. A fuel tank after the axle
  5. Turning the round round
  6. One turn
  7. How Paul would chain it
  8. Make the round of crates
  9. Ship it