1. Ignore this question from 2012 as it deals with material we have not discussed this year.
2. Write a program, that creates a list $t$ with 6 values, 0.1, 0.2, ..., 0.6. Compute a corresponding list $y$ of $y(t)$ values using the formula: $$y(t) = v_0t − gt^2,$$ where $v_0=6.0$ and $g=9.8$.
t = [0.1*i for i in range(1, 7)]
v0 = 6.0
g = 9.8
y = [v0*ti-g*ti**2 for ti in t]
t1 = []
for ti, yi in zip(t, y):
t1.append([ti, yi])
print "%8s%8s"%("t", "y")
for pair in t1:
print "%8g%8g"%(pair[0], pair[1])
t y 0.1 0.502 0.2 0.808 0.3 0.918 0.4 0.832 0.5 0.55 0.6 0.072
3. The factorial of n, written as n!, is defined as: $$n! = n(n − 1)(n − 2)...2\cdot1,$$ with the special cases $$1! = 1, 0! = 1.$$ For example, $4! = 4\cdot3\cdot2\cdot1 = 24$, and $2! = 2\cdot1 = 2$.
def fact(n):
if type(n) != int:
raise ValueError("value must be of type int")
if n < 0:
raise ValueError("value must be positive")
if n<2:
return 1
product = 1
for i in range(1, n+1):
product *= i
return product
# Let's show that it works
for i in range(5):
print "%d! = %d"%(i, fact(i))
0! = 1 1! = 1 2! = 2 3! = 6 4! = 24
4. A table of temperatures and densities, in units of degrees ($C$) and $kg/m^3$, are given in the file data/density_air.dat Write a program that reads in the data from file into a list for temperature (first column) and density (second column) and plots the variation of density against temperature.
%pylab inline
from pylab import *
file = open("data/density_air.dat")
tlist = []
dlist = []
for line in file:
words = line.split()
if len(words) != 2:
continue
try:
t = float(words[0])
d = float(words[1])
except:
continue
tlist.append(t)
dlist.append(d)
tarray = array(tlist)
darray = array(dlist)
plot(tarray, darray)
xlabel("Temperature (Celsius)")
ylabel("Density ($kg/m^3$)")
title("Density of air at different temperatures, at 1 atm pressure")
legend(("Air", ))
Populating the interactive namespace from numpy and matplotlib
<matplotlib.legend.Legend at 0x10b6ef1d0>
5. Based on the data in the file data/constants.txt, make a dictionary where the keys are the names of the physical constant and the values are a tuple containing the numerical value and the units.
file = open("data/constants.txt", "r")
constants = {}
for line in file:
try:
name = line[0:27].strip()
words = line[27:].split()
value = float(words[0])
units = words[1]
except:
continue
constants[name] = (value, units)
print constants
{'Planck constant': (6.6260755e-34, 'J*s'), 'elementary charge': (1.60217733e-19, 'C'), 'speed of light': (299792458.0, 'm/s'), 'electron mass': (9.1093897e-31, 'kg'), 'Avogadro number': (6.0221367e+23, '1/mol'), 'proton mass': (1.6726231e-27, 'kg'), 'gravitational constant': (6.67259e-11, 'm**3/kg/s**2'), 'Boltzmann constant': (1.380658e-23, 'J/K')}