Paul's Python CoursePPC

Vectorisation

Not met yet

Arithmetic and comparisons on an array happen to every item at once, with no loop: marks / 20 * 100 turns every mark into a percentage, and marks == 0 gives an array of True and False. Functions like np.abs work the same way, and .sum() on a True/False array counts the Trues. It is shorter, and far faster, because the work runs as compiled code over numbers of one type stored side by side, instead of Python handling each number in turn.

Try it

main.py

Output

Press Run and what your program prints shows up here.

Easy to get wrong

  • Thinks arithmetic on a NumPy array needs a loop, so array * 2 or array > 60 is an error.
  • Thinks comparing an array with a number gives a single True or False, rather than one for each item.
  • Thinks a NumPy array behaves like a list, so * repeats it and + joins two arrays end to end.

Where it comes up