📖
Introduction to programming with Python
  • Introduction to programming with Python 3
  • Preface
    • Common misconceptions about learning to program
    • The Hard truth about learning to program
    • Personal qualities for success
  • 1 - The way of the program
    • Python Programming Language
    • The first program
    • What is debugging?
    • Glossary
    • Exercises
  • 2 - Variables, expressions and statements
    • Values, types and variables
    • Common Built-in data types
    • Expressions
    • Code Format
    • Debugging
    • Glossary
    • Exercises
  • 3 - Functions
    • Python "built-in" Functions
    • Math Functions
    • Composition
    • User Defined Functions
    • PEP 8 Recommendations
    • Debugging
    • Glossary
    • Exercises
  • 4 - Conditionals
    • Boolean expressions
    • Conditional statements
    • PEP 8 Recommendations
  • 5 - Iteration
    • The while statement
    • The for statement
    • break and continue statements
    • Nested Loops
    • PEP 8 Recommendations
    • Debugging
    • Glossary
    • Exercises
  • 6 - A short introduction to testing: Building Reliable Software
  • 7 - A deeper dive into Strings, Lists and Tuples
    • More on Strings
    • More on Lists
    • More on Tuples
    • Debugging
    • Glossary
    • Exercises
  • 8 - A deeper look at Functions in Python
    • Function Preconditions and Postconditions
    • Positional and Keywords arguments
    • Nested Functions
    • Scope of a variable
    • Recursion
    • Functions' side effects
    • Glossary
    • Exercises
  • 9 - Code Documentation
    • Basics of Commenting Code
    • Documenting Code via Python Docstring
  • 10 - Sets and dictionaries
    • Sets
    • Dictionaries
    • Which data structure should I use?
    • Debugging
    • Glossary
    • Exercises
  • 11 - File I/O
    • Read/Write to a file
    • File management
    • Debugging
    • Glossary
    • Exercises
  • 12 - Handling Errors and Exceptions
  • 13 - Writing modules
  • 14 - Classes
    • Classes and Objects
    • Classes and Functions
    • Classes and Methods
    • Pythonic Magic: Understanding and Implementing Dunder Methods
    • Glossary
    • Exercises
  • 15 - Python's Type Hinting
  • Acknowledgements
Powered by GitBook
On this page
  • Exercise 1: printing a grid (revisited)
  • Exercise 2: Srinivasa Ramanujan infinite series
Edit on GitHub
  1. 5 - Iteration

Exercises

Exercise 1: printing a grid (revisited)

This can be done using only the print statements and other features we have learned so far.

  1. Write a function two_by_two_grid that draws a grid like the following:

+ - + - +
|   |   |
+ - + - +
|   |   |
+ - + - +

This time, you should use iteration

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.

Answer
def two_by_two_grid():
    for i in range(2):
        print('+', '-', '+', '-', '+')
        print('|', ' ', '|', ' ', '|')
    print('+', '-', '+', '-', '+')
  1. Write another function n_by_n_grid(size) to draw a similar grid with four rows and four columns.

Answer
def n_by_n_grid(size):
    grid = ''
    for row in range(size):
        odd_line = ''
        even_line = ''
        for column in range(size):
            odd_line += '+ - '
            even_line += '|   '
        odd_line += '+\n'
        even_line += '|\n'
        grid += odd_line + even_line
    grid += odd_line
    print(grid)

Note: This solution is overly complex, and one could wonder if the use of for loops is wise. It is important to familiarise ourselves with manipulating string to build the expected output. A more readable implementation of the function is given below:

def n_by_n_grid (size):
    odd_line = '+ - ' * size + '+\n'
    even_line = '|   ' * size + '|\n'
    grid = (odd_line + even_line) * size + odd_line
    print(grid)
  1. Write a more generic function x_by_y_grid(rows, cols) that draws a similar grid with rows rows and cols columns.

Exercise 2: Srinivasa Ramanujan infinite series

1π=229801∑k=0∞(4k)!(1103+26390k)(k!)43964k\frac{1}{\pi} = \frac{2\sqrt{2}}{9801} \sum^\infty_{k=0} \frac{(4k)!(1103+26390k)}{(k!)^4 396^{4k}}π1​=980122​​k=0∑∞​(k!)43964k(4k)!(1103+26390k)​

Write a function estimate_pi() that uses this formula to compute and return an estimate of π\piπ. 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 10−1510^{-15}10−15). You can check the result by comparing it to math.pi.

Answer

You will notice that the solution has two functions. The second function compute_term(k) is a convenience function that computes a single term of the series. Convenience functions are used to make the code easier to read. As you can see, the function estimate_pi() needs to compute the term of a series in two places (line 11 and 15). Rather than duplicating the code (remember it is bad practice), I have created a function and called it twice.

import math

def estimate_pi():
    """return the apporximation of PI using Srinivasa Ramanujan's 
    infinite series.

    Returns:
        float: the apporximation of PI
    """
    k = 0
    term = compute_term(k)
    inverse_pi = term
    while term > 1e-15:
        k = k + 1
        term = compute_term(k)
        inverse_pi += term
    inverse_pi *= (2 * pow(2, 0.5)) / 9801
    return 1 / inverse_pi


def compute_term(k):
    """compute a single term of the summation of Srinivasa Ramanujan 
    infinite series.

    Args:
        k (int): the index of the term's series

    Returns:
        float: the kth term of the summation
    """
    output = (math.factorial(4*k)* (1103 + 26390 * k))
    output /= pow(math.factorial(k), 4) * pow(396, 4*k)
    return output

Note also that the index k is incremented at the start of the loop (line 14) rather than the end. This is to ensure that the term k=0 is not computed twice.

PreviousGlossaryNext6 - A short introduction to testing: Building Reliable Software

Last updated 1 year ago

The brilliant mathematician Srinivasa Ramanujan found an that can be used to generate a numerical approximation of π\piπ:

Finally, the code is documented via docstring. You can learn more about docstring and documenting your code in the chapter "".

infinite series
Code documentation