Solutions
1.5.1. Solutions#
Solution to Exercise 1.16
Set n to 10
Set f to 1
Repeat until n equals 1:
Set f to f times n
Decrease n by 1
Print f
n = 10
f = 1
while n > 1:
f = f * n
n = n - 1 # or n -= 1
print(f)
Solution to Exercise 1.17
NB You should test your answer with a variety of values for a
, b
and c
to check that it is working correctly. At least one test for each of the three type of solution.
a = 1
b = -1
c = -12
discriminant = b**2 - 4 * a * c
if discriminant > 0:
print("The solutions are x =", (-b + discriminant**0.5)/(2*a), "and x =", (-b - discriminant**0.5)/(2*a))
elif discriminant == 0:
print("The solution is x =", -b/(2*a))
else:
print("There are no real solutions")
Solution to Exercise 1.18
Set value of n
Set value of m
Set i to 0
Repeat while n is greater than m:
Subtract m from n
Increase i by 1
Display i and n
n = 13
n_original = n
m = 3
i = 0
while n > m:
n = n - m
i += 1
print(n_original, "divided by", m, "equals", i, "remainder", n)
It should be reasonably easy to follow the instructions in order to produce the correct code to perform the calculation. The only tricky part is to maintain the original value of t
in a new variable t_orig
so that we can include it in the final print statement.
t = 1000000
t_orig = t
s = t % 60
t = t // 60
m = t % 60
t = t // 60
h = t % 24
d = t // 24
print(t_orig, " seconds is ", d, " days ", h, ":", m, ":", s, sep="")