05.lecture.menti.solutions

_澳门葡京手机版app下载

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.

  1. correct.
  2. end is not included so this prints [0, 5, 10]
  3. the print statement is indented and thus will be executed inside the loop, this will print the growing list multiple times
  4. 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]
  1. print(arange(3, 11, 2))
  2. print(range(3, 13, 2))
  3. print(arange(3, 13, 2))
  4. print(range(3, 11, 2))
Answer. The correct answer is the 3rd alternative, arange(3, 13, 2)

Solution.

  1. This will give [3 5 7 9], don't forget that the last increment is not counted in python
  2. This would give a range object, we want an array
  3. This is the correct answer, arange(3, 13, 2)
  4. 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?

  1. print(20 % x)
  2. print(20% * x)
  3. print(x - 0.8 * x)
  4. print(0.2 * x)
Answer. Option 3 and 4 are correct

Solution.

  1. This is in fact valid python, but gives the reamined when 20 is diveded by x
  2. This gives a syntax error
  3. This is correct (!)
  4. 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

  1. \( x_n = 1.5 \times x_{n} - 15 \)
  2. \( x_{n+1} = 1.5 \times x_{n-1} - 15 \)
  3. \( x_n = 1.5 \times x_{n-1} - 15 \)
  4. \( x_n = \frac{x_{n+1}}{1.5} + 15 \)
Answer. Option 3 is correct

Solution.

  1. has two time \( x_n \)
  2. has \( x_{n+1} \) and \( x_{n-1} \) so \( x_n \) is calculated based on \( x_{n-2} \)
  3. is correct, \( x_n \) is calculated based on \( x_{n-1} \)
  4. kind of gives the same values but this is not how these equations are written up.

Publisert 18. sep. 2017 15:59 - Sist endret 18. sep. 2017 16:30