Exercises 5 β
These exercises focus on using arrays and dictionaries.
As with the previous exercises, whenever youβre asked to declare a function, itβs up to you to choose appropriate parameters, argument labels, and return values. Also, include at least one function call with every function you declare, to show that you know how to call the function.
Exercise 5.1 β
Declare a function to calculate the sum of an array of numbers.
Exercise 5.2 β
Declare a function that takes an array of numbers and returns a new array where the order of the elements is reversed.
This is exactly what the reversed
method of type Array
does. Your solution shouldnβt rely on this method; the exercise is to implement it yourself.
Exercise 5.3 β
Declare a function that takes an array of numbers and returns a new array where the elements are sorted from small to large.
This is exactly what the sorted
method of type Array
does. Your solution shouldnβt rely on this method; the exercise is to implement it yourself.
Exercise 5.4 β
Declare a function characters(in:)
that checks which characters occur in a string and returns the number of times each of these characters occur.
Like arrays and dictionaries, strings are collections. This means you can use a for-in
loop to iterate over the characters in a string:
var string = "some string"
for character in string {
// ...
}
Youβll need this to solve the exercise.
Exercise 5.5 β
Declare a function words(in:)
that checks which words occur in a string and returns the number of times each of these words occur.
Exercise 5.6 β
Declare a function stats(for:)
that returns the number of lines, words, and characters in a string.