Exercises
Exercise 1: printing a grid (revisited)
This can be done using only the print
statements and other features we have learned so far.
Write a function
two_by_two_grid
that draws a grid like the following:
+ - + - +
| | |
+ - + - +
| | |
+ - + - +
Hint:
>>> print('line 1 \nline 2')
line 1
line 2
>>> print('line 1' + '\n' + 'line 2')
line 1
line 2
>>>
A print
statement all by itself ends the current line and goes to the next line.
Write another function
n_by_n_grid(size)
to draw a similar grid with four rows and four columns.
Write a more generic function
x_by_y_grid(rows, cols)
that draws a similar grid withrows
rows andcols
columns.
Exercise 2: Srinivasa Ramanujan infinite series
The brilliant mathematician Srinivasa Ramanujan found an infinite series that can be used to generate a numerical approximation of :
Write a function estimate_pi()
that uses this formula to compute and return an estimate of . It should use a while
loop to compute terms of the summation until the last term is smaller than 1e-15
(which is Python notation for ). You can check the result by comparing it to math.pi
.
Last updated