Command Palette

Search for a command to run...

Hectal
Phase 14: Working with Data: NumPy and pandas
Python · Exercise 1 of 6Next
Beginner

Turn a vector into a unit vector

Write a function normalise(v) that takes a NumPy vector (a 1-D array of numbers) and returns a new vector that points the same way but has length 1. To do that, divide the vector by its length. The length of a vector is its norm, which np.linalg.norm(v) gives you (Topic 14.5).

Edge case: a vector of all zeros has length 0, and dividing by 0 would give nan. For that input, return the zeros unchanged (an all-zero vector of the same size).

Then print the normalised version of np.array([3.0, 4.0]). It should print [0.6 0.8].

What Check tests

  1. An all-zero vector comes back as zeros, not nan
  2. normalise([3, 4]) is [0.6, 0.8]
  3. The result has length 1
  4. The direction is unchanged
  5. The input array is not changed

Stuck? One hint at a time

The solution unlocks after your first Check. Try first: that is where the learning happens.

main.py
Sign in to run your code.

Output

Press Run to see what your program prints.