Exercises¶
Write a fruitful function
sumTo(n)
that returns the sum of all integer numbers up to and including n. SosumTo(10)
would be1+2+3...+10
which would return the value 55. Use the equation (n * (n + 1)) / 2.
1def sumTo(n):
2# your code here
3
(ex_5_7)
141from test import testEqual
2
3def sumTo(n):
4result = (n * (n + 1)) / 2
5return result
6
7# Now lets see how well this works
8t = sumTo(0)
9print("The sum from 1 to 0 is",t)
10t = sumTo(10)
11print("The sum from 1 to 10 is",t)
12t = sumTo(5)
13print("The sum from 1 to 5 is",t)
14
(q7_answer)
Write a function areaOfCircle(r) which returns the area of a circle of radius r. Make sure you use the math module in your solution.
121from test import testEqual
2
3def areaOfCircle(r):
4# your code here
5
6t = areaOfCircle(0)
7testEqual(t,0)
8t = areaOfCircle(1)
9testEqual(t,math.pi)
10t = areaOfCircle(100)
11testEqual(t,31415.926535897932)
12
(ex_5_8)
Rewrite the function
sumTo(n)
that returns the sum of all integer numbers up to and including n. This time use the accumulator pattern.
31def sumTo(n):
2# your code here
3
(ex_5_13)
141def sumTo(n):
2sum = 0
3for i in range(1,n+1):
4sum = sum + i
5return sum
6
7# Now lets see how well this works
8t = sumTo(0)
9print("The sum from 1 to 0 is",t)
10t = sumTo(10)
11print("The sum from 1 to 10 is",t)
12t = sumTo(5)
13print("The sum from 1 to 5 is",t)
14
(q13_answer)
Write a function called
mySqrt
that will approximate the square root of a number, call it n, by using Newton’s algorithm. Newton’s approach is an iterative guessing algorithm where the initial guess is n/2 and each subsequent guess is computed using the formula: newguess = (1/2) * (oldguess + (n/oldguess)).
31
2
3
(ex_5_14)
Write a function called
myPi
that will return an approximation of PI (3.14159...). Use the Leibniz approximation.
31
2
3
(ex_5_15)
171def myPi(iters):
2''' Calculate an approximation of PI using the Leibniz
3approximation with iters number of iterations '''
4pi = 0
5sign = 1
6denominator = 1
7for i in range(iters):
8pi = pi + (sign/denominator)
9sign = sign * -1 # alternate positive and negative
10denominator = denominator + 2
11
12pi = pi * 4.0
13return pi
14
15pi_approx = myPi(10000)
16print(pi_approx)
17
(q15_answer)
Write a function that takes in input 10 numbers and returns the minimum, the sum, the maximum, and the average.
Note
This workspace is provided for your convenience. You can use this activecode window to try out anything you like.
(scratch_02)