Some versions of the program for calculating the formula $$F = \frac{9}{5}C + 32$$ are listed below. Determine which versions will not work correctly and explain why in each case.
C = 21; F = 9/5*C + 32; print F # This will not work as expected because "9/5" will give a value of 1, not 1.8, due to integer division.
C = 21.0; F = (9/5)*C + 32; print F # Same as above
C = 21.0; F = 9*C/5 + 32; print F # This works fine
C = 21.0; F = 9.*(C/5.0) + 32; print F # This works fine
C = 21.0; F = 9.0*C/5.0 + 32; print F # This works fine
C = 21; F = 9*C/5 + 32; print F # This will not work because of integer division problems in the expression "C/5".
C = 21.0; F = (1/5)*9*C + 32; print F # This will not work because of integer division problems in the expression "1/5".
C = 21; F = (1./5)*9*C + 32; print F # This works fine
53 53.0 69.8 69.8 69.8 69 32.0 69.8
We define the following nested list:
q = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h']]
Index this list to extract 1) the letter a; 2) the list ['d', 'e', 'f']; 3) the last element h; 4) the d element. Explain why q[-1][-2] has the value g.
q = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h']]
print q[0][0] # Select the first list in q, then the first element in that list.
print q[1] # Select the entire second list in q. Remember that the second element has an index of 1 because Python indexing starts at 0.
print q[len(q)-1][1] # Remember: index 0 corresponds to the first element, and index len(q)-1 corresponds to the last element (of q).
print q[1][0] # First element of the second list in q.
# Both "q[len(q)-1]" and "q[-1]" can be used to extract the last element in q.
# Then, within the sub-list q[-1], the element with index "-2" is the second last element.
# So q[-1][-2] selects the last list in q, and the second last element within that list.
a ['d', 'e', 'f'] h d
The standard Python function called sum takes a list as argument and computes the sum of the elements in the list:
sum([1,3,5,-5])
4
Implement your own version of sum.
def sum_new(l):
s = 0 # A variable to hold the sum as we loop over the elements in the list l
for element in l:
s += element # Add each element onto the running total 's'.
return s # Return the result
print sum_new([1, 3, 5, -5])
4
Consider the list q defined earlier. Construct a double for loop (i.e. a loop within a loop) to print out all of the elements in the nested list.
q = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h']]
for i in range(0, len(q)):
sublist = q[i]
for j in range(0, len(sublist)):
print "q[%d][%d] = %s" % (i, j, q[i][j])
q[0][0] = a q[0][1] = b q[0][2] = c q[1][0] = d q[1][1] = e q[1][2] = f q[2][0] = g q[2][1] = h
As an egg cooks, the proteins first denature and then coagulate. When the temperature exceeds a critical point, reactions begin and proceed faster as the temperature increases. In the egg white the proteins start to coagulate for temperatures above 63 C, while in the yolk the proteins start to coagulate for temperatures above 70 C. For a soft boiled egg, the white needs to have been heated long enough to coagulate at a temperature above 63 C, but the yolk should not be heated above 70 C. For a hard boiled egg, the center of the yolk should be allowed to reach 70 C. The following formula expresses the time $t$ it takes (in seconds) for the center of the yolk to reach the temperature $T_y$ (in Celsius degrees):
$$t = \frac{M^{2/3}c\rho^{1/3}}{K\pi^2(4\pi/3)^{2/3}}\ln\left[0.76\frac{T_o - T_w}{T_y - T_w}\right]$$Here, $M, \rho, c$ and $K$ are properties of the egg: $M$ is the mass, $\rho$ is the density, $c$ is the specific heat capacity, and $K$ is thermal conductivity. Relevant values are $M$ = 47 g for a small egg and $M$ = 67 g for a large egg, $\rho$ = 1.038 g cm$^{-3}$, $c$ = 3.7 J g$^{-1}$K$^{-1}$, and $K$ = 5.4 $\times$ 10$^{-3}$ W cm$^{-1}$ K$^{-1}$. Furthermore, $T_w$ is the temperature (in C degrees) of the boiling water, and $T_o$ is the original temperature (in C degrees) of the egg before being put in the water. Implement the formula in a program, set $T_w$ = 100 C and $T_y$ = 70 C, and compute $t$ for a large egg taken from the fridge ($T_o$ = 4 C) and from room temperature ($T_o$ = 20 C).
from math import pi, log
def t(Tw, Ty, To):
# Tw: Temperature of the water
# Ty: Desired temperature of the yolk
# To: Initial temperature of the egg
rho = 1.038 # g cm^{-3}
M = 67 # g
K = 5.4e-3 # W cm^{-1} K^{-1}
c = 3.7 # J g^{-1} K^{-1}
t = (M**(2.0/3.0)*c*rho**(1.0/3.0))/(K*(pi**2)*(4.0*pi/3.0)**(2.0/3.0))*log(0.76*(To - Tw)/(Ty - Tw))
return t
print "Time required when To = %d degrees: %.2f seconds." % (4, t(100.0, 70.0, 4)) # To = 4
print "Time required when To = %d degrees: %.2f seconds." % (20, t(100.0, 70.0, 20)) # To = 20
Time required when To = 4 degrees: 396.58 seconds. Time required when To = 20 degrees: 315.22 seconds.
The factorial of $n$, written as $n!$, is defined as
$$n! = n(n − 1)(n − 2) \cdots 2 \cdot 1,$$with the special cases
$$1! = 1,$$$$0! = 1.$$
For example, $4! = 4 \cdot 3 \cdot 2 \cdot 1 = 24$, and $2! = 2 \cdot 1 = 2$. Write a function fact(n) that returns $n!$. Return 1 immediately if $n$ is 1 or 0, otherwise use a loop to compute $n!$.
def fact(n):
if(n == 1 or n == 0):
return 1
else:
product = 1 # This variable keeps track of the product n * (n-1) * (n-2) * ... * 1
while n > 1:
product *= n
n -= 1 # Keep decreasing n until we reach 1, then return the result held in the variable 'product'.
return product
print "%d! = %d" % (4, fact(4))
print "%d! = %d" % (2, fact(2))
print "%d! = %d" % (1, fact(1))
4! = 24 2! = 2 1! = 1
Add in a try-except block to the function fact(n). An exception should be thrown/raised if the number n is negative. If an exception occurs, your program should print a helpful error message and quit.
def fact(n):
try:
if(n < 0):
raise ValueError
elif(n == 1 or n == 0):
return 1
else:
product = 1 # This variable keeps track of the product n * (n-1) * (n-2) * ... * 1
while n > 1:
product *= n
n -= 1 # Keep decreasing n until we reach 1, then return the result held in the variable 'product'.
return product
except ValueError:
raise ValueError("n must be greater than or equal to 0.")
sys.exit(1)
print "%d! = %d" % (-1, fact(-1)) # This should cause a ValueError exception.
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-21-8c51e0075d79> in <module>() 15 sys.exit(1) 16 ---> 17 print "%d! = %d" % (-1, fact(-1)) # This should cause a ValueError exception. <ipython-input-21-8c51e0075d79> in fact(n) 12 return product 13 except ValueError: ---> 14 raise ValueError("n must be greater than or equal to 0.") 15 sys.exit(1) 16 ValueError: n must be greater than or equal to 0.
Some object is moving along a path in the plane. At $n$ points of time we have recorded the corresponding $(x, y)$ positions of the object: $(x_0, y_0), (x_1, y_1), \ldots, (x_{n-1}, y_{n-1})$. The total length $L$ of the path from $(x_0, y_0)$ to $(x_{n-1}, y_{n-1})$ is the sum of all the individual line segments $(x_{i-1}, y_{i-1})$ to $(x_i, y_i)$, $i = 1, \ldots, n-1$:
$$L = \sum_{i=1}^{n-1}{\sqrt{(x_i - x_{i-1})^2 + (y_i - y_{i-1})^2}}.$$Make a function pathlength(x, y) for computing $L$ according to the formula. The arguments $x$ and $y$ hold all the $x_0, \ldots, x_{n-1}$ and $y_0, \ldots, y_{n-1}$ coordinates, respectively. Test the function on a triangular path with the four points (1, 1), (2, 1), (1, 2), and (1, 1).
from math import sqrt
def pathlength(x,y):
L = 0
for i in range(1, len(x)):
L += sqrt( (x[i] - x[i-1])**2 + (y[i] - y[i-1])**2 )
return L
x = [1, 2, 1, 1]
y = [1, 1, 2, 1]
print pathlength(x, y)
3.41421356237