Exercise 1: Lists and loops
Which of the alternatives gives the following output?
[0, 5, 10, 15]
1
list = []
for i in range(0, 20, 5):
list.append(i)
print(list)
2
list = []
for i in range(0, 15, 5):
list.append(i)
print(list)
3
list = []
for i in range(0, 20, 5):
list.append(i)
print(list)
4
list = []
for i in range(0, 15, 5):
append.list(i)
print(list)
Answer. 1
Solution.
In function range(start, end, step)
, start
is the number that you start with (including number start
),
end
is the number that you end with (not including number end
)
and step
is the number that is the interval between the previous and following numbers.
- correct.
-
end
is not included so this prints[0, 5, 10]
- the
print
statement is indented and thus will be executed inside the loop, this will print the growing list multiple times -
append
is used after the name of the list
Exercise 2: Array vs List 1
a) Which of the following will produce the given output:
[3 5 7 9 11]
-
print(arange(3, 11, 2))
-
print(range(3, 13, 2))
-
print(arange(3, 13, 2))
-
print(range(3, 11, 2))
arange(3, 13, 2)
Solution.
- This will give
[3 5 7 9]
, don't forget that the last increment is not counted in python - This would give a range object, we want an array
- This is the correct answer,
arange(3, 13, 2)
- Same as nr.2, we want an array, not a range object
Exercise 3: Percentage and fraction
a)
Which python command prints 20% of the value of x
?
-
print(20 % x)
-
print(20% * x)
-
print(x - 0.8 * x)
-
print(0.2 * x)
Solution.
- This is in fact valid python, but gives the reamined when 20 is diveded by
x
- This gives a syntax error
- This is correct (!)
- Correct and the 'best' way to do this
Exercise 4: Difference equations
a) Which of the following difference equations corresponds to this 'rule':
Each next step, multiply the value of the previous step with 1.5 and substract 15
- \( x_n = 1.5 \times x_{n} - 15 \)
- \( x_{n+1} = 1.5 \times x_{n-1} - 15 \)
- \( x_n = 1.5 \times x_{n-1} - 15 \)
- \( x_n = \frac{x_{n+1}}{1.5} + 15 \)
Solution.
- has two time \( x_n \)
- has \( x_{n+1} \) and \( x_{n-1} \) so \( x_n \) is calculated based on \( x_{n-2} \)
- is correct, \( x_n \) is calculated based on \( x_{n-1} \)
- kind of gives the same values but this is not how these equations are written up.