Skip to content
Snippets Groups Projects
Commit 71e11b31 authored by Michele Nottoli's avatar Michele Nottoli
Browse files

Added chapter 3 with some extra content on arrays.

parent f528cb20
No related branches found
No related tags found
No related merge requests found
%% Cell type:markdown id:4fe99eff-729a-4d93-ab82-487e5143bae5 tags:
# Advanced Data Types
%% Cell type:markdown id:ffd395d4-fbc2-4c81-b9ce-68b4babd901b tags:
## Arrays
%% Cell type:markdown id:1aedb913-e484-43d8-b21d-0bc57f1a22c5 tags:
An array is a sequence of values. The values in an array are called elements or sometimes items and they can be of any type. We will see more about arrays in the next lesson, for now we simply consider the basics.
There are several ways to create a new array; the simplest is to enclose the elements in square brackets (`[ ]`):
%% Cell type:code id:ddfba3ab-f520-4617-a937-3809cc1f06b6 tags:
``` julia
a1 = [10, 20, 30, 40]
@show a1
a2 = ["a", "b", "c"]
@show a2;
```
%% Cell type:markdown id:cb15aba4-a6d4-45db-9783-501ac4b8fb63 tags:
The first example is an array of four integers. The second is an array of three strings. The elements of an array don’t have to be the same type. The following array contains a string, a float, an integer, and another array:
%% Cell type:code id:56814d39-2d81-4f2d-bf63-a1a3030d2ccf tags:
``` julia
a3 = ["spam", 2.0, 5, [10, 20]]
@show a3;
```
%% Cell type:markdown id:7a18ac29-c477-4d58-bb22-2566b2248d7e tags:
An array within another array is nested.
An array that contains no elements is called an empty array; you can create one with empty brackets, `[]`.
The function typeof can be used to find out the kind of the array:
%% Cell type:code id:f53616f1-910d-47ab-be2f-68127dd6f2e6 tags:
``` julia
@show typeof(a1)
@show typeof(a2)
@show typeof(a3);
```
%% Cell type:markdown id:fd99f8ca-a174-4b25-a12b-764d7807f3a6 tags:
The syntax for accessing the elements of an array is the same as for accessing the characters of a string—the bracket operator. The expression inside the brackets specifies the index. Remember that the indices start at 1:
%% Cell type:code id:4b1262f3-672d-421f-bf1a-4dd860407a7a tags:
``` julia
a1[1]
```
%% Cell type:markdown id:8dcd70d7-467f-497a-b94e-e9aae0ec738a tags:
Arrays are mutable. When the bracket operator appears on the left side of an assignment, it identifies the element of the array that will be assigned:
%% Cell type:code id:8442b5f4-bc86-4620-a4bc-a10322b254da tags:
``` julia
a1[1] = 5
@show a1;
```
%% Cell type:markdown id:26d27784-832e-45eb-b421-03acb522a619 tags:
Array indices work according to these rules:
- Any integer expression can be used as an index.
- If you try to read or write an element that does not exist, you get a BoundsError.
- The keyword `end` points to the last index of the array.
The `∈` operator also works on arrays:
%% Cell type:code id:58f736f7-adfb-43ed-b825-3e031638d760 tags:
``` julia
@show 10 in a1;
```
%% Cell type:markdown id:db829f89-95f0-478e-9193-938ca27691c1 tags:
The most common way to traverse the elements of an array is with a `for` loop.
%% Cell type:code id:7bd5fdef-3212-46de-af51-44f1407e53f0 tags:
``` julia
for element in a1
println(element)
end
```
%% Cell type:markdown id:720bf843-5d4d-4c50-8917-193046dcaa3b tags:
This works well if you only need to read the elements of the array. As changing the variable `element` has no effect on the array elements.
If you want to write or update the elements, you need the indices. A common way to do that is to use the built-in function eachindex:
%% Cell type:code id:a6415603-4d90-4cc2-bd07-0a93f135db33 tags:
``` julia
@show a1
for i in eachindex(a1)
a1[i] = a1[i] * 2
end
@show a1;
```
%% Cell type:markdown id:7969b8f9-335a-4bd2-82f7-1d9795234ed5 tags:
## Dictionaries
%% Cell type:markdown id:ea8518c1-8e1d-4532-8055-e04c3aa3e7c4 tags:
A dictionary contains a collection of indices, which are called keys, and a collection of values. Each key is associated with a single value. The association of a key and a value is called a key-value pair or sometimes an item.
The function `Dict` creates a new dictionary with no items. Because Dict is the name of a built-in function, you should avoid using it as a variable name.
%% Cell type:code id:59ae8d17-a6f6-4210-95bc-0e7492bc8a7a tags:
``` julia
eng2de = Dict()
```
%% Cell type:code id:28490ea3-c4d3-4e4d-915f-612ad36c9472 tags:
``` julia
eng2de["one"] = "ein";
```
%% Cell type:markdown id:f2aff40c-6dcb-421a-b67f-1662c5bf4702 tags:
You can also initialize a dictionary with items as:
%% Cell type:code id:92fc203b-4ba8-432a-a541-c4ccf3292195 tags:
``` julia
eng2de = Dict("one" => "ein", "two" => "zwei", "three" => "drei")
```
%% Cell type:markdown id:c52d24af-ec90-4b8c-bdd9-988129a7fa81 tags:
Dictionaries are mutable, meaning that it is always possible to modify their elements, add new key-value pairs or removing existing ones.
%% Cell type:code id:22b295dc-994e-4bbc-ac8d-da5ab9e73493 tags:
``` julia
eng2de["four"] = "VIER"
@show eng2de
eng2de["four"] = "vier"
@show eng2de
delete!(eng2de, "four")
@show eng2de;
```
%% Cell type:markdown id:01513ad2-3083-4c89-adca-ccc8a88d93d4 tags:
In general, the order of the key-value pairs is unpredictable. However this is not important, as the values are always accessed using the keys.
%% Cell type:code id:e9e4c5b9-9539-4294-a6ec-0a29fb76bf7b tags:
``` julia
eng2de["two"]
```
%% Cell type:markdown id:9944dbbd-478b-4ae1-ac89-e16be08a0868 tags:
If the key isn’t in the dictionary, you get an exception:
%% Cell type:code id:8221269b-7a8f-4cfd-ab8e-0aa4fd6c962d tags:
``` julia
eng2de["four"]
```
%% Cell type:markdown id:a545abaa-78dc-4625-84e9-03b1c8beaaf8 tags:
The `length` function works on dictionaries; it returns the number of key-value pairs:
%% Cell type:code id:0e242667-b921-4242-bdcc-cbcac14909b2 tags:
``` julia
length(eng2de)
```
%% Cell type:markdown id:8e42655b-f2a0-41f0-be90-015ebfeafdb9 tags:
The function `keys` returns a collection with the keys of the dictionary:
%% Cell type:code id:3236f973-d3fa-42ba-a1c0-41e0002446cb tags:
``` julia
keys(eng2de)
```
%% Cell type:markdown id:acfa7044-5695-4af8-b4bc-320c8a48a220 tags:
Now you can use the `∈` operator to see whether something appears as a key in the dictionary:
%% Cell type:code id:1fdeb10c-0d84-4c22-b734-d68e2eafe375 tags:
``` julia
@show "one" keys(eng2de)
@show "four" keys(eng2de);
```
%% Cell type:markdown id:986919d6-4f27-4fad-b222-20697bf6af40 tags:
To see whether something appears as a value in a dictionary, you can use the function `values`, which returns a collection of values, and then use the `∈` operator:
%% Cell type:code id:ab90dad1-61d0-4dbd-b829-a354c13fcb71 tags:
``` julia
@show "ein" values(eng2de)
@show "vier" values(eng2de);
```
%% Cell type:markdown id:049c9dfd-1e51-4898-98e5-a4b812d0bba2 tags:
### Loops over dictionaries
You can traverse the keys of the dictionary in a `for` statement.
%% Cell type:code id:e7062d3f-2125-4ecd-ab13-d04944a71fe1 tags:
``` julia
function print_dictionary(dic)
for key in keys(dic)
println(key, " ", dic[key])
end
end
print_dictionary(eng2de)
```
%% Cell type:markdown id:cf27195c-e601-49ca-b03d-63162bf59bce tags:
Again, the keys are in no particular order. To traverse the keys in alphabetically sorted order, you can combine `sort` and `collect`:
%% Cell type:code id:6d52aeba-3c7e-405c-bcfe-d76e37e94f51 tags:
``` julia
function print_dictionary_sorted(dic)
for key in sort(collect(keys(dic)))
println(key, " ", dic[key])
end
end
print_dictionary_sorted(eng2de)
```
%% Cell type:markdown id:8daa9d3e-19de-4415-ba6c-6aeb174b38fa tags:
### Exercises
- Write a function that given a string as input counts how many times each letter appears. Use a dictionary.
%% Cell type:code id:aba1978b-e675-48a7-89aa-75553db70537 tags:
``` julia
```
%% Cell type:markdown id:3a9b281f-6cc0-4d39-b9e2-d816823f9873 tags:
## Tuples and named tuples
%% Cell type:markdown id:a722109e-86cc-44e3-9256-a3e93a1668f5 tags:
A tuple is a sequence of values. The values can be of any type, and they are indexed by integers. The tuples are immutable and each element can have its own type.
%% Cell type:code id:8502cf2e-8bea-4707-811c-f4e6e1de3c8f tags:
``` julia
t = 'a', 'b', 'c', 'd', 'e'
```
%% Cell type:markdown id:d01f5647-a240-4620-9a3a-782835aca39c tags:
Although it is not necessary, it is common to enclose tuples in parentheses:
%% Cell type:code id:bfa31b99-bf9d-49bb-babc-fe8a65248429 tags:
``` julia
t = ('a', 'b', 'c', 'd', 'e')
```
%% Cell type:markdown id:3fa935e0-0611-4b8a-982c-329c33a74f99 tags:
To create a tuple with a single element, you have to include a final comma:
%% Cell type:code id:cb1bea15-2b80-43b2-be8e-27507d550fca tags:
``` julia
t1 = ('a',)
@show typeof(t1)
t2 = ('a')
@show typeof(t2);
```
%% Cell type:markdown id:193457ac-4e4b-4e58-8c28-6d8b4331d532 tags:
Another way to create a tuple is the built-in function tuple. With no argument, it creates an empty tuple:
%% Cell type:code id:952acafe-ca5d-4b58-8969-224b0fe3a28f tags:
``` julia
t3 = tuple()
@show typeof(t3)
t4 = tuple(1, 'a', π)
@show typeof(t4);
```
%% Cell type:markdown id:729c3597-1a35-4a26-ae7a-6dadee31daeb tags:
Using the bracket operator it is possible to access an element. Note, differently from other programming languages (for example C, C++, Python) in Julia the first element is 1.
%% Cell type:code id:9817c28f-428d-4d5b-8384-608f9b4d763d tags:
``` julia
t4[2]
```
%% Cell type:markdown id:aeda8602-f9da-4173-a692-54e2e9a0e178 tags:
But if you try to modify one of the elements of the tuple, you get an error:
%% Cell type:code id:cfc94cc9-832c-45d2-85b8-aaf789f33f6a tags:
``` julia
t4[2] = 'b'
```
%% Cell type:markdown id:b9f13b5c-9e61-46b9-a47d-f90199bd7bd2 tags:
Because tuples are immutable, you can’t modify the elements.
%% Cell type:markdown id:a10cb9a7-8f44-44f8-831f-178b780e4ac9 tags:
Strictly speaking, a function can only return one value, but if the value is a tuple, the effect is the same as returning multiple values. For example, if you want to divide two integers and compute the quotient and remainder, it is inefficient to compute x ÷ y and then x % y. It is better to compute them both at the same time.
The built-in function `divrem` takes two arguments and returns a tuple of two values, the quotient and remainder. You can store the result as a tuple:
%% Cell type:code id:d1dde137-036f-4b93-8010-13b3e835ebd8 tags:
``` julia
t = divrem(7, 3)
```
%% Cell type:markdown id:ea615dbd-effb-4442-b160-20e7c9b6c22e tags:
Alternatively, we can use tuple assignment to store the elements separately:
%% Cell type:code id:c4969556-7945-43c9-8b96-1ea1032cbb3c tags:
``` julia
q, r = divrem(7, 3)
@show q r;
```
%% Cell type:markdown id:4574e191-aaa8-4834-8837-54947d6ddf30 tags:
### Gather and scatter
Functions can take a variable number of arguments. A parameter name that ends with `...` gathers arguments into a tuple. For example, `printall` takes any number of arguments and prints them one by line:
%% Cell type:code id:43f8c7ad-5ac2-425e-a50f-c45624bb3d8a tags:
``` julia
function printall(args...)
for arg in args
println(arg)
end
end
printall(1)
printall(1, 2.0, '3')
```
%% Cell type:markdown id:eb662374-fe83-49d7-a5be-d9582d037ad1 tags:
The complement of gather is scatter. If you have a sequence of values and you want to pass it to a function as multiple arguments, you can use the `...` operator. For example, `divrem` takes exactly two arguments; it doesn’t work with a tuple:
%% Cell type:code id:bf55fc10-8432-41e3-bd6c-2244c8c96513 tags:
``` julia
t = (7, 3)
divrem(t)
```
%% Cell type:markdown id:d05def39-3244-4acd-a082-a7ee532f8f1d tags:
But if you scatter the tuple, it works:
%% Cell type:code id:e7df53bc-6b2d-4501-9ca8-61e3cb79eb1a tags:
``` julia
t = (7, 3)
divrem(t...)
```
%% Cell type:markdown id:2cf01c32-9d1b-4e83-9375-f737e51c58ed tags:
### Dictionaries and Tuples
%% Cell type:markdown id:00e97ccc-8e64-4eef-84be-85a266eb3490 tags:
Dictionaries can be used as iterators that iterate the key-value pairs. You can use it in a `for` loop like this:
%% Cell type:code id:ed483334-36d0-4700-b178-cd9dc5f12189 tags:
``` julia
d = Dict('a'=>1, 'b'=>2, 'c'=>3);
for (key, value) in d
println(key, " ", value)
end
```
%% Cell type:markdown id:dcb05236-810a-410b-aaa0-0cb431e3e64f tags:
It is common to use tuples as keys in dictionaries. For example, a telephone directory might map from last-name, first-name pairs to telephone numbers. Assuming that we have defined last, first and number, we could write:
%% Cell type:markdown id:e5462d35-fa68-42d8-ba00-c5dd1747c557 tags:
`directory[last, first] = number`
%% Cell type:markdown id:9980d710-392b-4716-b44d-98e6c5c8b838 tags:
### Named tuples
%% Cell type:markdown id:e514c4bd-c17c-44f4-a89f-88154cc1bf6c tags:
Named tuples are a special type of tuple in Julia where each element has a specific name associated with it. This allows you to access elements by their names, making the code more readable and self-explanatory.
%% Cell type:code id:78fb5959-407a-4128-9287-bb9d455f22dc tags:
``` julia
person = (name = "Michele", age = 28, city = "Stuttgart")
```
%% Cell type:markdown id:63075b2d-ef86-48e4-8f84-981f81fdece0 tags:
Named tuples are immutable, however it is possible to update the content, or to add new elements, by creating a new version. For example:
%% Cell type:code id:ecd22e07-5ba3-4f11-bc77-d967a6fc3fe8 tags:
``` julia
updated_person = (person..., age = 29)
updated_person = (person..., number = "0711 ...")
```
%% Cell type:code id:3409d1a3-85da-470c-bc5b-4ba9ecb53591 tags:
``` julia
```
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment