Last updated: 2025-02-05
Please finish the “Apply what you learned” section before you begin these tasks.
Solutions will be made available at the end of class, in the same page as the solutions to the “Apply what you learned” exercises.
Create a function quadsolve
that takes in the parameters a
, b
, and c
of a quadratic equation ax^2 + bx + c = 0 and applies the quadratic formula to determine the solutions.
Example usage:
= quadsolve(1, 4, -5)
result
# prints [-5, 1]
print(result)
Write a function mmult2
that takes in two 2 by 2 matrices A and B (as 1-dimensional lists of size 4) and returns A\times B (also as a 1-dimensional list of size 4).
Example usage:
= mmult2([1, 2, 3, 4], [5, 6, 7, 8])
result
# prints [19, 22, 43, 50]
print(result)
Create a function mmult
to perform n by n square matrix multiplication:
raise Exception('<your text here>')
or assert <boolean statement>
) if the inputs are not the same length or are not square numbersExample:
= mmult([1, 2, 3, 4, 5, 6, 7, 8, 9], [9, 8, 7, 6, 5, 4, 3, 2, 1])
result
# prints [30, 24, 18, 84, 69, 54, 138, 114, 90]
print(result)
random
functionUse the following line to import the random
function from the standard random
library Python provides:
from random import random
You can call the random
function like this:
= random() x
This will generate a random decimal number between 0 and 1, and assign the value to the variable x
.
Make a game where the user needs to guess a (whole) number between 0 and 100:
random
function mentioned aboveExample:
Enter a number: 43
Too low!
Enter a number: 67
Too low!
Enter a number: 88
Too high!
Enter a number: 71
Too low!
Enter a number: 74
Correct! It took you 5 guesses.
random.random()
Recall the formulas for the area of a square and of a circle:
Use these formulas and the random
function described above to estimate the value of \pi, by estimating frequency of random points in a square falling within a circle inscribed within it.
Write a function minmoves
that takes two parameters - two squares in algebraic chess notation - and returns the minimum number of moves required for a bishop to move from the first square to the second square.
Example:
= minmoves('a8', 'a6')
result1 print(result1) # prints 2
= minmoves('a7', 'a6')
result2 print(result2) # prints -1
Create a similar function for knights.
Example:
= minmovesKnight('a8', 'a6')
result1 print(result1) # prints 2
= minmovesKnight('a7', 'a6')
result2 print(result2) # prints 3