Sõnastik

Anaconda
Array Comprehension
Command line
Dictionary
Function
Immutable
List Comprehension
Package
Respectively
Floating point representation
Syntax

Valige vasakul üks märksõnadest ...

Programming in JuliaIteration

Lugemise aeg: ~25 min

We have already seen one way of doing something to each element in a collection: the array comprehension

.

In this array comprehension, we iterate over the pairs of the dictionary

to produce a new list. Although list comprehensions are very useful, they are not flexible enough to cover all our iteration needs. A much more flexible tool is the for loop.

For statements

The code above could also be rewritten as follows:

The statement for item in collection: works as follows: the first element of collection is assigned to item, and the block indented below the for statement is executed. Then, the second element of collection is assigned to item, the indented block is executed again, etc., until the end of the collection is reached.

We can nest for statements. For example, suppose we have a matrix represented as an array of arrays, and we want to sum all of the matrix entries. We can do that by iterating over the rows and then iterating over each row:

Exercise
Suppose you have imported a function file_bug_report with two parameters: id and description. Suppose also that you have a Dict called bugs whose keys are ids and whose values are strings representing descriptions. Write a loop which performs the action of filing each bug report in the dictionary.

Solution. We loop over the pairs of the dictionary:

Exercise
Write a function

called sumorial which takes a positive integer n as an argument and sums of the integers 1 to n using a loop.

Solution. We loop through 1:n and add as we go.

While statements

The Collatz conjecture is one of the easiest-to-state unsolved problems in mathematics. Starting from any given positive integer, we halve it if it's even and triple it and add one if it's odd. The Collatz conjecture states that repeatedly applying this rule always gets us to the number 1 eventually. For example, the Collatz sequence starting from 17 is

17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1

If we want to write a Julia function which returns the Collatz sequence for any given starting number, we face a problem: we don't know from the start how many steps it will take to reach 1, so it isn't clear how we could use a for loop. What we want to do is execute a block of code until a given condition is met. Julia provides the while loop for this purpose.

The expression which appears immediately following the while keyword is called the condition, and the block indented below the while statement is the body of the loop. The rules of the language stipulate the following execution sequence for a while statement: the condition is evaluated, and if it's true, then the body is executed, then condition is evaluated again, and so on. When the condition returns false, the loop is exited. An exit can also be forced from within the body of the while loop with the keyword break.

Exercise
Newton's algorithm for finding the square root of a number n starts from 1 and repeatedly applies the function x\mapsto \frac{1}{2}(x + n/x). For example, applying this algorithm to approximate \sqrt{2}, we get

1, 3/2, 17/12, 577/408, ...

This algorithm converges very fast: 577/408 approximates \sqrt{2} with a relative error of about 0.00015%.

Write a function newtonsqrt which takes as an argument the value n to square root and applies Newton's algorithm until the relative difference between consecutive iterates drops below 10^{-8}.

Note that 10^{-8} can be represented in Julia using scientific notation 1e-8.

Solution. We keep up with two separate variables, which we call x and old_x, to compare the most recent two iterates:

Exercises

Exercise
Write a function which prints an n \times n checkerboard pattern of x's and o's.

Note: \n in a string literal represents the "newline" character. You'll need to print this character after each row you've printed.

Solution. We loop through the rows and use an if statement to print a different output depending on whether the row is even-numbered or odd-numbered.

Exercise
Write a function which prints Pascal's triangle up to the $n$th row, where the top row counts as row zero. You might want to use a helper function print_row(n,row) to manage the responsibility of printing each row, as well as a helper function next_row(row) to calculate each row from the previous one.

Example output, for n = 4:

        1
      1   1
    1   2   1
  1   3   3   1
1   4   6   4   1

Note: there's no solution to this one, but you can do it on your own!

Bruno Bruno

Welcome to Data Gymnasia! I’m Bruno, your personal tutor. graduation-cap

Our content is divided into small steps. You have to complete the activities to reveal what’s next.