1. Lab03a.py - Approximating pi
#
# Name:
# File: Lab03a.py
# Date: January 24, 2008
#
# Desc: Approximating pi
using the Gregory Series
#
import math
def main():
# Program Title
print
print"Lab03a - Approximating pi"
print
#
Get input from user
n = input("Enter the number of terms to use: ")
#
Calculate approximation to pi
myPi = 0.0;
for k in range(n):
if (k
% 2 == 0):
myPi = myPi + 4.0/(2*k + 1)
else:
myPi = myPi - 4.0/(2*k + 1)
#
Display results
print
print
"pi is approximately =", myPi
print
"This differs from math.pi by ", math.pi - myPi;
print
main()
2. Lab03b.py - Computing C(n,k) = “n choose k”
#
# Name:
# File: Lab03b.py
# Date: January 24, 2008
#
# Desc: Calculating n
choose k
#
def main():
#
Program Title
print
print
"Calculating n choose k"
print
# Get input from user
n, k = input("Enter n and k separated by a comma: ")
# compute n!
nFactorial = 1;
for i in range(1, n+1):
nFactorial = nFactorial * i
# compute k!
kFactorial = 1;
for i in range(1, k + 1):
kFactorial = kFactorial * i
# compute (n-k)!
lFactorial = 1
for i in range(1, n - k + 1):
lFactorial = lFactorial * i
# compute C(n,k) = n!/(k! *
(n-k)!)
c = nFactorial/(kFactorial*lFactorial)
# Display
results
print
print n,
"choose", k, "=", c
print
main()
3. Lab03d.py - The 153 Problem
#
# Name:
# File: Lab03d.py
# Date: January 24, 2008
#
# Desc: Generating the
sequence from the 153 problem
def main():
# Program Title
print
print
"The 153 Problem"
print
# Get starting value
for sequence
n = input("Enter a 1 to 4 digit integer: ")
print
# Using an
ask-before-iterating loop calculate next value
again = 1
while
(again == 1):
d1 = n
% 10; #
one's digit
d2 = n
/ 10 % 10 #
ten's digit
d3 = n
/ 100 % 10 #
hundred's digit
d4 = n
/ 1000 % 10 #
thousand's digit
n =
d4**3 + d3**3 + d2**3 + d1**3 # next number
print
"Answer: ",n
print
again
= input("Again? Enter 1 for yes - 0 for no:
")
print
main()