Albion College

CS 171

Introduction to Computer Science I & Lab

Fall 2021

Lab 3: Loops

Lab 3: Loops

Goals and Objectives

The main goal this lab is for you to get a more practice with Pythons's loop control structures, in particular, for loops and nested loops. You will work more with loops to gain a better appreciation for their power and capabilities.

Task

You will create a simple class which contains functions that compute some simple computations.

Background

Iteration is the ability to perform a computation many times. These computations can be nearly identical, often with a slight difference in the coding. Recognizing and using patterns is a key element in computer science. Identifying the patterns present in these computations will allow you to easily perform the required computations.

Loops are everywhere! Armed with the ability to use the selection and iteration statements, you can write almost any program.

Examples:

Introductions

Introduce yourself to your lab partner(s). Tell your lab partner(s) about your favorite things to do in Albion.

Download the lab

Download the source file Lab03.py. It contains the stubs of Python functions. Open it in the online Python environment.

Getting Started

In this lab, you will practice writing loops. You should start off with s1 driving and s2 navigating. Complete the functions in Lab03.py. You should change driver/navigator roles after each method is completed.

Seek help as soon as you are experiencing difficulty with this assignment.
Do not wait until the deadline to seek help!

# Lab 3 # YOUR NAMES HERE import math # compute 1 + 2 + 3 + ... + n # use for loop and range function def sum(n): return None # returns 1x1 + 2x2 + 3x3 + 4x4 + ... + nxn # use for loop and range function def sumSquares(n): return None # returns 1 + 3 + 5 + ... + 2*n-1 # use for loop and range function def sumOdds(n): return None # compute n! = 1 x 2 x 3 x ... x n # use for loop and range function # don't use any math library functions def factorial(n): return None # return 2 to the nth power # use for loop and range function # don't use any math library functions # dont use the ** operator def p2(n): return None # returns 1 + 2 + 4 + 8 + 16 + ... + 2**n # use for loop and range function # don't use any math library functions def p2sum(n): return None # return x to the nth power # use for loop and range function # don't use any math library functions # dont use the ** operator def power(x, n): return None # returns an approximation to pi using n terms # use for loop and range function def pi(n): return None # returns x**k/k! # use for loop and range function # don't use any math library functions # dont use the ** operator # dont use your factorial or power functions def term(x, k): return None # returns approximation to the sine of x using n terms # use for loop and range function # don't use any math library functions # dont use the ** operator # dont use your factorial or power functions # use your term function def sin(x, n): return None # returns approximation to the cosine of x using n terms # use for loop and range function # don't use any math library functions # dont use the ** operator # dont use your factorial or power functions # use your term function def cos(x, n): return None # returns the nth Fibonacci number # 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144 # fibo(0) = 0 # fibo(1) = 1 # fibo(2) = fibo(1) + fibo(0) # fibo(3) = fibo(2) + fibo(1) # fibo(4) = fibo(3) + fibo(2) # use a while loop, no recursion def fibo(n): return None # A zoologist orders a shipment of animals. # The shipment contains spiders (S), beetles (B), mice (M), and canaries (C). # The shipment contained a total of n legs. How many of each animal is present? # Count the number of solutions to this problem: 8S + 6B + 4M + 2C = n # use nested for loops def legs(n): return None # Testing code def main(): print("sum") print(sum(10), "should be 55") print(sum(100), "should be 5050") print() print("sumSquares") print(sumSquares(1), "should be 1") print(sumSquares(5), "should be 55") print() print("sumOdds") print(sumOdds(1), "should be 1") print(sumOdds(10), "should be 100") print() print("factorial") print(factorial(0), "should be 1") print(factorial(1), "should be 1") print(factorial(5), "should be 120") print(factorial(20), "should be 2432902008176640000") print() print("p2") print(p2(0), "should be 1") print(p2(1), "should be 2") print(p2(5), "should be 32") print(p2(10), "should be 1024") print(p2(20), "should be 1048576") print() print("p2sum") print(p2sum(0), "should be 1") print(p2sum(6), "should be 127") print() print("power") print(power(2,3), "should be 8") print(power(3,4), "should be 81") print(power(6,7), "should be", 6**7) print() print("pi") print(pi(1), "should be close to 3.14159265358979323844") print(pi(1000), "should be closer to 3.14159265358979323844") print(pi(1000000), "should be even closer to 3.14159265358979323844") print() print("term") print(term(3,5), "should be 2.025") print() print("sin") print(sin(math.pi/2,1), "should be close to", math.sin(math.pi/2)) print(sin(math.pi/2,1000), "should be closer to", math.sin(math.pi/2)) print() print("cos") print(cos(math.pi,1), "should be close to", math.cos(math.pi)) print(cos(math.pi,1000), "should be closer to", math.cos(math.pi)) print() print("fibo") print(fibo(0), "should be 0") print(fibo(1), "should be 1") print(fibo(2), "should be 1") print(fibo(7), "should be 13") print(fibo(12), "should be 144") print() print("legs") print(legs(0), "should be 1") print(fibo(1), "should be 0") print(fibo(8), "should be 5") print(fibo(100), "should be 1154") print() main()

Use a for loop to solve each of these problems. You may not use while statement. The main method in Lab03.py contains 3 test cases for most functions you need to complete. For each method, you should verify some of the test cases and consider adding others you feel might help test your program.

There are several independent functions in this lab. These are listed in roughly easiest to hardest, but if you get stuck on a part, you should consider trying the next step. You will write functions as follows.

  1. Complete the function which has a single integer parameter \(n\) and and returns an integer which the sum of the integers from 1 through \(n\) using a for loop. $$\text{sum} = \underbrace{1 + 2 + \cdots + i + \cdots + n}_{n \text{ terms}} = \sum_{i=1}^n i.$$
  2. Complete the function in the above program to compute sum of the first \(n\) squares using a single for loop, $$\text{sum} = \underbrace{1^2 + 2^2 + \cdots + i^2 + \cdots + n^2}_{n \text{ terms}} = \sum_{i=1}^n i^2.$$ Recall the circumflex (^) does not mean exponentiation in Python. One way to compute \(x^2\) is by using x*x or x**2.
  3. Complete the function in the above program to compute the sum of the first \(n\) odd numbers using a single for loop, $$\text{sum} = \underbrace{1 + 3 + \cdots + (2 i - 1) + \cdots + (2 n - 1)}_{n \text{ terms}} = \sum_{i=1}^n (2 i - 1).$$
  4. Complete the function in the above program to compute the sum of the first \(n+1\) powers of 2 (starting at 0) using a single for loop, $$\text{sum} = \underbrace{2^0 + 2^1 + \cdots + 2^i + \cdots + 2^n}_{n+1 \text{ terms}} = \sum_{i=0}^n 2^i.$$ Use your previous function to compute \(2^i\).
  5. Complete the function in the above program to compute \(n!\) using a single for loop and returns the result. Recall that \(0!=1\) and $$n! = \underbrace{1 \times 2 \times \cdots \times i \times \cdots \times n}_{n \text{ terms}} = \prod_{i=1}^n i\ .$$
  6. Complete the function in the above program to compute \(2^n\) using a single for loop and returns the result. Recall that \(2^0=1\) and $$2^n = \underbrace{2 \times 2 \times \cdots \times 2 \times \cdots \times 2}_{n \text{ terms}} = \prod_{i=1}^n 2\ .$$
  7. Compute \(\pi\) using \(n+1\) terms in the expression below $$\pi = 4 - \dfrac{4}{3} + \frac{4}{5} - \frac{4}{7} + \frac{4}{9} - \cdots = \sum_{i=0}^\infty \frac{4 \cdot (-1)^{i}}{2i+1}.$$ Because it would take an infinite amount of time and computer memory to compute this using an infinite number of terms, we will only use \(n+1\) terms to get the approximation $$\pi \approx \underbrace{4 - \dfrac{4}{3} + \frac{4}{5} - \frac{4}{7} + \frac{4}{9} - \cdots + \frac{4 \cdot (-1)^{n}}{2n+1}}_{n+1 \text{ terms}} = \sum_{i=0}^n \frac{4 \cdot (-1)^{i}}{2i+1}.$$ This approximation comes from the Taylor series of the arctangent function and will approach \(\pi\) as the number of terms increases.

    Note that the terms alternate between positive and negative. One can achieve this by using an additional multiplier variable, say m that gets multiplied by -1 inside the loop so that its value alternates between 1 and -1 on successive iterations.
  8. Complete the function called term that takes a double parameter \(x\) and an int parameter \(k\) and returns a double that represents $$\dfrac{x^k}{k!} = \underbrace{\left(\dfrac{x}{1}\right) \left(\dfrac{x}{2}\right) \cdots \left(\dfrac{x}{i}\right) \cdots \left(\dfrac{x}{k}\right)}_{k \text{ terms}}$$ Note that for large values of \(k\), computing \(k!\) can be complicated, so that computing individual terms is a better way to perform this computation. Remember that the computer is only a model of our number system!
  9. Another definition of the sine function is given by the following infinite sum of terms: $$ \sin(x) = x - \dfrac{x^3}{3!} + \dfrac{x^5}{5!} - \dfrac{x^7}{7!} + \cdots = \sum_{i=0}^{\infty} \left((-1)^{i} \underbrace{\left(\dfrac{x^{(2i+1)}}{(2i+1)!}\right)}_{\text{term}(x,2i+1)}\right)$$ As with computing \(\pi\), we will use an approximation with \(n+1\) terms $$ \sin(x) = \underbrace{x - \dfrac{x^3}{3!} + \dfrac{x^5}{5!} - \dfrac{x^7}{7!} + \cdots + (-1)^{i}\dfrac{x^{(2n+1)}}{(2n+1)!}}_{n+1 \text{ terms}} = \sum_{i=0}^{n} \left((-1)^{i} \left(\dfrac{x^{(2i+1)}}{(2i+1)!}\right)\right)$$ Compute \(\sin(x)\) using \(n\) terms and compare it to the value returned from the system using math.sin(x) for values of x between 0 and \(\pi\). Use the term function in the previous step.
  10. Another definition of the cosine function is given by the following infinite sum of terms: $$ \cos(x) = 1 - \dfrac{x^2}{2!} + \dfrac{x^4}{4!} - \dfrac{x^6}{6!} + \cdots = \sum_{i=0}^{\infty} \left((-1)^{i} \left(\dfrac{x^{(2i)}}{(2i)!}\right)\right)$$ As with the sine function, we will use an approximation with \(n+1\) terms $$ \cos(x) \approx \underbrace{1 - \dfrac{x^2}{2!} + \dfrac{x^4}{4!} - \dfrac{x^6}{6!} + \cdots + (-1)^{i}\dfrac{x^{(2i)}}{(2i)!}}_{n+1 \text{ terms}} = \sum_{i=0}^{n} \left((-1)^{i} \left(\dfrac{x^{(2n)}}{(2n)!}\right)\right)$$ Use as many terms as you can in your computation. Compute \(\cos(x)\) in this way and compare it to the value returned from the system using math.cos(x) for values of x between 0 and \(\pi\). Use the term function in the previous step.
  11. Add to the above program to compute the nth Fibonacci number. Fibonacci numbers, Fi are defined in the following way. F1 = 1, F2 = 1, and Fi = Fi-1+Fi-2, when i > 2. The Fibonacci numbers are 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, and so on. Do this using a single for loop.
    F1=1 
    F2=1 
    F3=2=1+1
    F4=3=2+1
    F5=5=3+2
         
    F6=8=5+3
         
    F7=13=8+5
    . . .
    Fi=  Fi-1+Fi-2
    . . .
    This is trickier than the previous steps because you will need to remember not just the current sum, but also the previous sum. Hint: use additional variables.
  12. A zoologist orders a shipment of animals. The shipment contains spiders, beetles, mice, and canaries. The shipment contained a total of \(N\) legs. How many of each animal is present? There are many solutions, but a computer program can easily generate and count all solutions. Add to the above program code which determines and counts all integer solutions to the general problem of \(N\) legs by using the equation $$8s + 6b + 4m + 2c = N$$ where \(s\), \(b\), \(m\), and \(c\) are between \(0\) and \(N\). You will need to nest four loops corresponding to \(s\), \(b\), \(m\), and \(c\). You will also need an if-else statement. Only output the total number of solutions and when finished. Note you may want to initially try small values of \(N\).

Have Fun!

Final Steps

When done, email you lab partner and instructor your lab (.py file).