Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 40 ยท Practice and Review

Practice Exercises with Solutions

Fifteen Julia exercises on arrays, broadcasting, dispatch, structs, iteration and performance, each with a worked solution and a runnable Python stand-in.

You learn Julia by writing it. This lesson gives you fifteen exercises, ordered from warm-ups to small design problems, covering arrays, broadcasting, dictionaries, structs, multiple dispatch, iteration and performance. Every exercise has a solution written in Julia, with the output a real Julia session prints shown in comments.

Julia is not installed on this site, so the Julia code is read-only. To get practice you can run, two stand-ins at the end port several exercises to Python and NumPy. Install Julia on your own machine (see Installing Julia and Using the REPL) and type the solutions in instead of pasting them; the typing is where the learning happens.

How to work through an exercise

Read it twice Say the input and output out loud first.
Try first Give it ten minutes before peeking.
Test small Check an input you can solve by hand.
Refactor Then compare with the solution below.
1 / 2

Part 1: Arrays and broadcasting

Exercise 1: Sum of odd squares

Write odd_square_sum(n) that returns the sum of the squares of all odd numbers from 1 to n.

JULIA
odd_square_sum(n) = sum(x^2 for x in 1:2:n)

odd_square_sum(10)   # 165  (1 + 9 + 25 + 49 + 81)

The range 1:2:n starts at 1 and steps by 2, so it never contains an even number. The generator inside sum does not build a temporary array. For n = 0 the range is empty and sum of an empty generator throws, so a robust version uses sum(x^2 for x in 1:2:n; init = 0).

Exercise 2: Reverse without and with mutation

Reverse a vector once so that the original survives, and once in place.

JULIA
v = [1, 2, 3, 4]
w = reverse(v)     # [4, 3, 2, 1], v is unchanged
reverse!(v)        # v is now [4, 3, 2, 1]

The ! is a convention: functions that modify an argument end in a bang. Allocation-free in-place variants matter in Performance Tips.

Exercise 3: Moving average

Given a vector, return the average of every window of three consecutive values.

JULIA
function moving_average(v)
    [sum(@view v[i:i+2]) / 3 for i in 1:length(v)-2]
end

moving_average([1, 2, 3, 4, 5])   # [2.0, 3.0, 4.0]

@view avoids copying each three-element slice. The result is a Vector{Float64} because / always produces a float for integers. Note that the loop bound is length(v) - 2: with 1-based indexing the last window starts at length(v) - 2.

Exercise 4: Center the columns of a matrix

Subtract each column's mean from that column, without a loop.

JULIA
A = [1 2; 3 4; 5 6]
centered = A .- sum(A; dims = 1) ./ size(A, 1)
# 3ร—2 Matrix{Float64}:
#  -2.0  -2.0
#   0.0   0.0
#   2.0   2.0

sum(A; dims = 1) gives a 1ร—2 row of column sums. Dividing by the row count gives the means, and .- broadcasts that single row against all three rows. This is the idea from Broadcasting and the Dot Syntax.

Exercise 5: Count the largest

Return how many elements of a vector equal its maximum.

JULIA
count_max(v) = count(==(maximum(v)), v)

count_max([3, 9, 2, 9, 9, 1])   # 3

==(x) builds a function that tests equality with x, which is exactly what count wants. Two passes over the data are fine here; a one-pass version would track the maximum and a counter in a loop.

Part 2: Collections and strings

Exercise 6: Word frequencies

Count how often each word appears, ignoring case.

JULIA
function word_counts(text)
    counts = Dict{String,Int}()
    for w in split(lowercase(text))
        counts[w] = get(counts, w, 0) + 1
    end
    counts
end

c = word_counts("the cat and The dog and the bird")
c["the"]   # 3
c["and"]   # 2

split without a delimiter splits on whitespace and returns SubStrings, which are converted to String keys on insertion. get(counts, w, 0) returns a default when the key is missing. To print in order, use sort(collect(c); by = last, rev = true).

Exercise 7: Unique and sorted

Return the sorted distinct values of a vector.

JULIA
sorted_unique(v) = sort!(unique(v))

sorted_unique([5, 1, 5, 3, 1])   # [1, 3, 5]

unique returns a new vector, so it is safe to sort it in place with sort!.

Part 3: Structs and dispatch

Exercise 8: A point and its distance

Define an immutable Point with two Float64 fields and a function for the distance between two points.

JULIA
struct Point
    x::Float64
    y::Float64
end

dist(a::Point, b::Point) = hypot(a.x - b.x, a.y - b.y)

dist(Point(0, 0), Point(3, 4))   # 5.0

The constructor converts the integer arguments to Float64 for you. hypot avoids overflow that a hand-written square root of squares could hit.

Exercise 9: Shapes with dispatch

Model circles and rectangles and give both an area. Add a generic describe that works for any shape.

JULIA
abstract type Shape end

struct Circle <: Shape
    r::Float64
end

struct Rect <: Shape
    w::Float64
    h::Float64
end

area(c::Circle) = pi * c.r^2
area(r::Rect) = r.w * r.h

describe(s::Shape) = "$(nameof(typeof(s))) with area $(round(area(s); digits = 2))"

describe(Rect(2, 3))   # "Rect with area 6.0"
describe(Circle(1))    # "Circle with area 3.14"

Adding a Triangle later means one new struct and one new area method; describe keeps working untouched. That is the payoff of multiple dispatch.

Exercise 10: Make a type add and print

Create a Vec2 that supports + and prints as (x, y).

JULIA
struct Vec2
    x::Float64
    y::Float64
end

Base.:+(a::Vec2, b::Vec2) = Vec2(a.x + b.x, a.y + b.y)
Base.show(io::IO, v::Vec2) = print(io, "(", v.x, ", ", v.y, ")")

Vec2(1, 2) + Vec2(0.5, 3)   # (1.5, 5.0)
sum([Vec2(1, 1), Vec2(2, 2)])   # (3.0, 3.0)
sum(Vec2[])                      # fails: no zero element for Vec2

Because + now works for Vec2, sum works on any non-empty vector of them. The empty sum fails, since Julia has no idea what an empty Vec2 total should be; adding Base.zero(::Vec2) = Vec2(0, 0) fixes that. Extending Base functions for your own types is not piracy.

Exercise 11: A generic maximum

Write largest(xs) that works for any non-empty vector of real numbers and refuses strings.

JULIA
function largest(xs::AbstractVector{T}) where {T<:Real}
    best = first(xs)
    for x in xs
        x > best && (best = x)
    end
    best
end

largest([3, 7, 2])        # 7
largest([1.5, -2.0])      # 1.5
largest(["a", "b"])       # MethodError: no method matching largest(::Vector{String})

The where {T<:Real} clause both names the element type and restricts it. AbstractVector accepts ranges, views and other array types, not just Vector.

Part 4: Iteration and performance

Exercise 12: Make a type iterable

Create a Countdown that counts from n to 1 in a for loop.

JULIA
struct Countdown
    from::Int
end

Base.iterate(c::Countdown, state = c.from) = state < 1 ? nothing : (state, state - 1)
Base.length(c::Countdown) = c.from

collect(Countdown(3))   # [3, 2, 1]
for n in Countdown(2)
    println(n)          # prints 2, then 1
end

iterate returns nothing when the loop is done, or a tuple of the current item and the next state. Defining length lets collect preallocate. The rules are in Interfaces and Iteration Protocols.

Exercise 13: Fix a type-unstable function

This function can return an Int or a Float64. Fix it so the return type depends only on the input type.

JULIA
clip_bad(x) = x > 0 ? x : 0.0      # Int input: Int or Float64

clip_good(x) = x > 0 ? x : zero(x) # always the type of x

With x = 5, clip_bad returns an Int; with x = -5 it returns a Float64. The compiler cannot know which, so it must box the result. zero(x) produces a zero of the same type, so @code_warntype clip_good(5) shows a single concrete return type. See How Julia Compiles Code.

Exercise 14: Column-major summation

Sum all elements of a matrix with explicit loops, in the cache-friendly order.

JULIA
function mysum(A::AbstractMatrix)
    s = zero(eltype(A))
    for j in axes(A, 2)          # columns in the outer loop
        for i in axes(A, 1)      # rows in the inner loop
            s += A[i, j]
        end
    end
    s
end

mysum([1 2; 3 4])   # 10

Julia stores matrices column by column, so the first index should vary fastest. Putting j outside and i inside walks memory sequentially. Starting s with zero(eltype(A)) keeps it the same type as the elements, so the accumulation stays type stable. Writing the loop inside a function (not at top level) is what lets the compiler specialize it.

Exercise 15: Parallel sum with tasks

Split a vector into four chunks and sum them in parallel, without sharing a mutable accumulator.

JULIA
function psum(v; nchunks = 4)
    chunks = Iterators.partition(v, cld(length(v), nchunks))
    tasks = map(c -> Threads.@spawn(sum(c)), chunks)
    sum(fetch.(tasks))
end

psum(1:1_000_000)   # 500000500000

Each task computes a partial sum and returns it, so no two tasks write to the same variable and there is no race condition. fetch waits for a task and returns its value. Start Julia with julia -t 4 to give it four threads; with one thread the answer is the same but nothing runs in parallel. More in Threads, Tasks and Distributed Computing.

Runnable stand-ins

Here are NumPy versions of exercises 3 and 4. They are not Julia, but the array thinking is the same: slice windows, broadcast one row against many.

Python Exercises 3 and 4 in NumPy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python's range(1, n + 1, 2) plays the part of 1:2:n. Notice the extra + 1: Python ranges exclude the end, Julia ranges include it, and that off-by-one is the classic trap when you switch between the two.

The second stand-in recreates exercise 9 (shapes) and exercise 12 (a custom iterator) in plain Python.

Python Shapes and a countdown in Python

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

singledispatch looks only at the first argument, which is enough here. Julia's version dispatches on all of them, as shown in Multiple Dispatch. The generator replaces Julia's iterate state tuple.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does largest(xs::AbstractVector{T}) where {T<:Real} reject a vector of strings?

    Dispatch finds no applicable method, so Julia raises a MethodError before any of the body runs.
  2. 2. In exercise 14, why is the row index in the inner loop?

    Consecutive elements of a column are adjacent in memory, so the inner loop over rows reads memory sequentially.
  3. 3. Why is clip_good(x) = x > 0 ? x : zero(x) better than x > 0 ? x : 0.0 for integers?

    The version with 0.0 returns an Int on one branch and a Float64 on the other, which defeats optimization.
  4. 4. How does exercise 15 avoid a race condition?

    With no shared mutable state, no two tasks can overwrite each other's work. The results are combined after fetch.

Summary

  • Practice by typing solutions yourself, predicting the output, then comparing.
  • Prefer broadcasting, @view and generators over explicit temporary arrays.
  • Model data with structs and behavior with methods; new types need new methods, not edits to old code.
  • Make return types depend only on input types (zero(x), eltype(A)) to keep code type stable.
  • Loop over the first index fastest, and give parallel tasks their own results to combine afterwards.

Next: study the traps behind several of these exercises in Common Mistakes and Gotchas.