Solutions to assignments:¶
Problem 1. Convert imperial to metric¶
weight_lbs = float(input("Please enter your weight in lbs: ")) # in pounds
weight_kg = weight_lbs * 0.45#<- put your code here!
print ('Weight in kilograms: ' + str(weight_kg))
Please enter your weight in lbs: 25 Weight in kilograms: 11.25
Fahrenheit converter¶
temp_far = float(input('Enter a temperature in Farenheit: '))
temp_cel = 5/9.0 * (temp_far - 32)
print ('Temperature in Celcius: ' + str(temp_cel))
Enter a temperature in Farenheit: 45 Temperature in Celcius: 7.222222222222222
Standard deviation¶
(a) Modify this code so that it prints the mean on the first line of its output and prints the standard deviation of the three numbers on the second line of its output. Remember that the standard deviation of a sample $x_1,x_2,\ldots,x_n$ with sample mean $\hat{x}=\sum_{i=1}^n x_i/n $ is defined to be:
from math import sqrt
x1 = float(input('Enter the first number: '))
x2 = float(input('Enter the second number: '))
x3 = float(input('Enter the third number: '))
xhat = (x1 + x2 + x3) / 3.0
print ('Mean: ', xhat)
std = sqrt(1/(3.0-1)*((x1 - xhat)**2+(x2 - xhat)**2+(x2 - xhat)**2))
print ('STD: ', std)
Enter the first number: 4 Enter the second number: 5 Enter the third number: 6 Mean: 5.0 STD: 0.7071067811865476
Problem 3. Calculator¶
import math
# Question (a)
radius = 5.
circle_perimeter = 2.*math.pi*radius # Replace me
circle_area = math.pi*radius**2. # Replace me
print ('A circle of radius ' + str(radius) + ' has a perimeter of ' + str(circle_perimeter) + ' and an area of ' + str(circle_area))
# Question (b)
# http://en.wikipedia.org/wiki/Golden_ratio
golden_ratio = (1.+math.sqrt(5))/2 # Replace me
print ('The golden ratio is equal to ' + str(golden_ratio))
# Question (c)
# http://en.wikipedia.org/wiki/Pentagonal_pyramid
side_length = 2.
pyramid_height = math.sqrt((5-math.sqrt(5))/10)*side_length
pyramid_area = (math.sqrt(25.+10.*math.sqrt(5))/4. + 5*math.sqrt(3.)/4.)*side_length**2. # Replace me
pyramid_volume = ((5. + math.sqrt(5))/24)*side_length**3.
print ('A regular pentagonal pyramid of side length ' + str(side_length) + ' has an height of ' + str(pyramid_height) + ', an area of ' + str(pyramid_area) + ' and a volume of ' + str(pyramid_volume) + '. Interesting, I suppose.')
# Question (d)
# http://en.wikipedia.org/wiki/List_of_fractals_by_Hausdorff_dimension
dodecahedron_fractal_dimension = math.log(20)/math.log(2+golden_ratio) # Replace me
cauliflower_fractal_dimension = math.log(13)/math.log(3) # Replace me
print ('A Sierpinski Dodecahedron has a fractal dimension of ' + str(dodecahedron_fractal_dimension) + ', how intriguing!')
print ('A cauliflower has a fractal dimension of ' + str(cauliflower_fractal_dimension))
if dodecahedron_fractal_dimension > cauliflower_fractal_dimension:
print ('The dodecahedron wins.')
else:
print ('The cauliflower wins. Obviously.')
A circle of radius 5.0 has a perimeter of 31.41592653589793 and an area of 78.53981633974483 The golden ratio is equal to 1.618033988749895 A regular pentagonal pyramid of side length 2.0 has an height of 1.0514622242382672, an area of 15.542163640200254 and a volume of 2.4120226591665967. Interesting, I suppose. A Sierpinski Dodecahedron has a fractal dimension of 2.329621716170345, how intriguing! A cauliflower has a fractal dimension of 2.3347175194727927 The cauliflower wins. Obviously.
Problem 4. Strings manipulation¶
# Question (a)
message = "uSiNg aPPrOpRiAtE cApiTaLISAtiOn iS iMpOrTaNt fOr yOuR rEaDerS' SANity"
lowercased = message.lower() # Replace me
uppercased = message.upper() # Replace me
sentencecased = message.capitalize() # Replace me
print (message + '\n' + lowercased + '\n' + uppercased + "\n" + sentencecased)
uSiNg aPPrOpRiAtE cApiTaLISAtiOn iS iMpOrTaNt fOr yOuR rEaDerS' SANity using appropriate capitalisation is important for your readers' sanity USING APPROPRIATE CAPITALISATION IS IMPORTANT FOR YOUR READERS' SANITY Using appropriate capitalisation is important for your readers' sanity
text = 'align me'
width = 20
stars = '*'*width
text_left = str.ljust(text, width) # Replace me
text_right = str.rjust(text, width) # Replace me
text_center = str.center(text, width) # Replace me
print ('I want this aligned properly! ' + '\n' + stars + '\n' + text_left + '\n' + text_right + '\n' + text_center + '\n' + stars)
I want this aligned properly!
********************
align me
align me
align me
********************
email = "Scientific Programming in Pyhton: The student will be able to write simple programs in pythons."
corrected = str.replace(str.replace(str.replace(email, 'Pyhton', 'Python'), 'pythons', 'Python'), 'python', 'Python') # Replace me
#print (email + '\n' + corrected)
email = "Scientific Programming in Pyhton: The student will be able to write simple programs in pythons."
email = email.split()
#print (email)
for i, word in enumerate(email):
print (i, word)
if email[i] == "pythons.":
email[i] = "Python."
elif email[i] == "Pyhton:":
email[i] = "Python:"
print (" ".join(email))
0 Scientific 1 Programming 2 in 3 Pyhton: 4 The 5 student 6 will 7 be 8 able 9 to 10 write 11 simple 12 programs 13 in 14 pythons. Scientific Programming in Python: The student will be able to write simple programs in Python.
Problem 5 Basics: Alphabet¶
(a) We’ll first start by making a list each of the upper and lower case letters in the English alphabet:
import string
uc = list(string.ascii_uppercase)
lc = list(string.ascii_lowercase)
print(uc,lc)
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
(b) Blank your full name from both lists, using a
forloop (it's easiest to first concatenate them):
both = uc + lc
name = "Jeremy Bentham"
for i in range(len(both)):
if both[i] in name:
both[i] = '*'
print (both)
['A', '*', 'C', 'D', 'E', 'F', 'G', 'H', 'I', '*', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '*', 'b', 'c', 'd', '*', 'f', 'g', '*', 'i', 'j', 'k', 'l', '*', '*', 'o', 'p', 'q', '*', 's', '*', 'u', 'v', 'w', 'x', '*', 'z']
both_sorted = sorted(both)
for index, letter in enumerate(both):
print (index, letter)
both_blanksremoved = both[10:]
print (both_blanksremoved)
0 A 1 * 2 C 3 D 4 E 5 F 6 G 7 H 8 I 9 * 10 K 11 L 12 M 13 N 14 O 15 P 16 Q 17 R 18 S 19 T 20 U 21 V 22 W 23 X 24 Y 25 Z 26 * 27 b 28 c 29 d 30 * 31 f 32 g 33 * 34 i 35 j 36 k 37 l 38 * 39 * 40 o 41 p 42 q 43 * 44 s 45 * 46 u 47 v 48 w 49 x 50 * 51 z ['K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '*', 'b', 'c', 'd', '*', 'f', 'g', '*', 'i', 'j', 'k', 'l', '*', '*', 'o', 'p', 'q', '*', 's', '*', 'u', 'v', 'w', 'x', '*', 'z']
blanks_removed = [letter for letter in list(string.ascii_uppercase)+list(string.ascii_lowercase) if letter not in 'Jeremy Bentham']
print (blanks_removed)
['A', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'b', 'c', 'd', 'f', 'g', 'i', 'j', 'k', 'l', 'o', 'p', 'q', 's', 'u', 'v', 'w', 'x', 'z']
Problem 6 Medium: Times tables¶
In this problem we’ll use for-loops, some lists and control how values are printed on screen, to produce a full times table (from 1 to 12).In this problem we’ll use for-loops, some lists and control how values are printed on screen, to produce a full times table (from 1 to 12).
# Part (a)
max_time = 13
number = 2
times_2 = []
# Here you could also iterate over range(1, max_time+1), I just did it differently
for i in range(max_time):
# Append to your new list
times_2.append(number*(i))
print (times_2)
def row(number, max_time):
'''Calculates the times row for a given number up to
a set maxium.'''
row = []
for i in range(1, max_time+1):
row.append(number*i)
return row
def print_row(row):
'''Prints a times table row'''
row_string = str(row[0]) + " | "
for i in row:
row_string = row_string + str(i) + ' '
print (row_string)
def print_header(max_time):
header = " " # Some initial whitespace
for i in range(1, max_time+1):
header = header + str(i) + ' '
print (header)
print (" " + "---"*max_time)
def times_table(max_time):
print_header(max_time)
for i in range(1,max_time+1):
print_row(row(i, max_time))
times_table(14)
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24]
1 2 3 4 5 6 7 8 9 10 11 12 13 14
------------------------------------------
1 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14
2 | 2 4 6 8 10 12 14 16 18 20 22 24 26 28
3 | 3 6 9 12 15 18 21 24 27 30 33 36 39 42
4 | 4 8 12 16 20 24 28 32 36 40 44 48 52 56
5 | 5 10 15 20 25 30 35 40 45 50 55 60 65 70
6 | 6 12 18 24 30 36 42 48 54 60 66 72 78 84
7 | 7 14 21 28 35 42 49 56 63 70 77 84 91 98
8 | 8 16 24 32 40 48 56 64 72 80 88 96 104 112
9 | 9 18 27 36 45 54 63 72 81 90 99 108 117 126
10 | 10 20 30 40 50 60 70 80 90 100 110 120 130 140
11 | 11 22 33 44 55 66 77 88 99 110 121 132 143 154
12 | 12 24 36 48 60 72 84 96 108 120 132 144 156 168
13 | 13 26 39 52 65 78 91 104 117 130 143 156 169 182
14 | 14 28 42 56 70 84 98 112 126 140 154 168 182 196
def row(number, max_time):
'''Calculates the times row for a given number up to
a set maximum.'''
row = []
for i in range(1, max_time+1):
row.append(number*i)
return row
def print_row(row):
'''Prints a times table row'''
row_string = str(row[0]).rjust(2) + "|"
for i in row:
row_string = row_string + str(i).rjust(3) + " "
print (row_string)
def print_header(max_time):
'''Prints the header for the times table'''
header = " " # Some initial whitespace
for i in range(1, max_time+1):
header = header + str(i).rjust(3) + " "
print (header)
print (" " + "-"*max_time*5)
def times_table(max_time):
'''Print a times table'''
print_header(max_time)
for i in range(1,max_time+1):
print_row(row(i, max_time))
times_table(20)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 ---------------------------------------------------------------------------------------------------- 1| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 2| 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 3| 3 6 9 12 15 18 21 24 27 30 33 36 39 42 45 48 51 54 57 60 4| 4 8 12 16 20 24 28 32 36 40 44 48 52 56 60 64 68 72 76 80 5| 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100 6| 6 12 18 24 30 36 42 48 54 60 66 72 78 84 90 96 102 108 114 120 7| 7 14 21 28 35 42 49 56 63 70 77 84 91 98 105 112 119 126 133 140 8| 8 16 24 32 40 48 56 64 72 80 88 96 104 112 120 128 136 144 152 160 9| 9 18 27 36 45 54 63 72 81 90 99 108 117 126 135 144 153 162 171 180 10| 10 20 30 40 50 60 70 80 90 100 110 120 130 140 150 160 170 180 190 200 11| 11 22 33 44 55 66 77 88 99 110 121 132 143 154 165 176 187 198 209 220 12| 12 24 36 48 60 72 84 96 108 120 132 144 156 168 180 192 204 216 228 240 13| 13 26 39 52 65 78 91 104 117 130 143 156 169 182 195 208 221 234 247 260 14| 14 28 42 56 70 84 98 112 126 140 154 168 182 196 210 224 238 252 266 280 15| 15 30 45 60 75 90 105 120 135 150 165 180 195 210 225 240 255 270 285 300 16| 16 32 48 64 80 96 112 128 144 160 176 192 208 224 240 256 272 288 304 320 17| 17 34 51 68 85 102 119 136 153 170 187 204 221 238 255 272 289 306 323 340 18| 18 36 54 72 90 108 126 144 162 180 198 216 234 252 270 288 306 324 342 360 19| 19 38 57 76 95 114 133 152 171 190 209 228 247 266 285 304 323 342 361 380 20| 20 40 60 80 100 120 140 160 180 200 220 240 260 280 300 320 340 360 380 400
times_table(10)
1 2 3 4 5 6 7 8 9 10 -------------------------------------------------- 1| 1 2 3 4 5 6 7 8 9 10 2| 2 4 6 8 10 12 14 16 18 20 3| 3 6 9 12 15 18 21 24 27 30 4| 4 8 12 16 20 24 28 32 36 40 5| 5 10 15 20 25 30 35 40 45 50 6| 6 12 18 24 30 36 42 48 54 60 7| 7 14 21 28 35 42 49 56 63 70 8| 8 16 24 32 40 48 56 64 72 80 9| 9 18 27 36 45 54 63 72 81 90 10| 10 20 30 40 50 60 70 80 90 100
Problem 7. Pascal’s triangle¶
This is a slight variation on the previous exercise. The goal is to generate Pascal's Triangle:

The rules to generate the triangle are quite simple:
- Each number is the sum of the two just above it, the above-left and the above-right one. (e.g. 5 on the last line is 1 + 4).
- The top and sides of the triangle are initialised with 1s.
Solution¶
We will use two nested loops, like the times table.
i is going to index my lines, j is going to index my columns.
In part (b), looking at the output for the triangle, you should see how a triangle is only a "half-square": using i and j for lines and columns still makes sense.
But now the second one is not going to go all the way up to number_lines (that would build a square), instead we stop j at the current value of i.
For example, on line 2, we need j to iterate over [0, 1]. On line 3, [0, 1, 2].
This is exactly what we do, except we have to be careful with the indices and how xrange/range behaves, so you will see slightly different arguments
number_lines = 10
triangle = [[1]]
for i in range(1, number_lines):
# Construct a new line in the triangle
triangle.append([])
# Iterate j up to the current i only, to get a triangle directly.
for j in range(i+1):
# Now we have to fill the triangle, according to the given rules.
if j == 0 or j == i:
# If we are on the sides of the triangle, we should write 1.
# The side is when j = 0 (left side) and j=i (right, its maximum value)
triangle[i].append(1)
else:
# If we are inside the triangle, we need to add the two numbers above us.
# When you look at the indices, and how the triangle looks in part (b),
# you should be able to see how I can access the correct numbers.
triangle[i].append(triangle[i-1][j-1] + triangle[i-1][j])
for t in triangle:
print (t)
[1] [1, 1] [1, 2, 1] [1, 3, 3, 1] [1, 4, 6, 4, 1] [1, 5, 10, 10, 5, 1] [1, 6, 15, 20, 15, 6, 1] [1, 7, 21, 35, 35, 21, 7, 1] [1, 8, 28, 56, 70, 56, 28, 8, 1] [1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
Print triangle nicely¶
Here I will have to do the same as in the Time Table, add spaces appropriately so that everything looks nice and aligned. Here I am using 'center', to center my string with spaces around it.
The subtle thing is to know the size each centered string should occupy.
I compute w: the length of the number-string, on the last line in the middle of the triangle. (in the example, '10', the right one.). The length of the number-string is really just the number of digits of this number (here 2) Then if this number is odd, I add 3 to it (it will become even now) If the number is even, I add 2 to it (it will stay even). this seems arbitrary, but will give me a nice result which looks balanced. You could just fix w to 3 or 5 and everything would look nice enough.
w = len(str(triangle[-1][len(triangle)//2]))
if w % 2 == 1:
w += 3
else:
w += 2
So now that I have computed the space taken by each element of the triangle, I can compute the size used by the "basis" of the triangle, so here the last line. The last line contains number_line elements, and each should take w space: we know the overall width of our triangle. Every line should now be centered with this width, and it will give my the proper result.
field = w*number_lines
pretty_triangle = []
for line in triangle:
items = []
for item in line:
items.append(str(item).center(w))
pretty_triangle.append(''.join(items).center(field))
for l in pretty_triangle:
print (l)
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1