%%html
<style>
.example1 {
height: 50px;
overflow: hidden;
position: relative;
}
.example1 h3 {
font-size: 3em;
color: red;
position: absolute;
width: 100%;
height: 100%;
margin: 0;
line-height: 50px;
text-align: center;
/* Starting position */
-moz-transform:translateX(100%);
-webkit-transform:translateX(100%);
transform:translateX(100%);
/* Apply animation to this element */
-moz-animation: example1 15s linear infinite;
-webkit-animation: example1 15s linear infinite;
animation: example1 15s linear infinite;
}
/* Move it (define the animation) */
@-moz-keyframes example1 {
0% { -moz-transform: translateX(100%); }
100% { -moz-transform: translateX(-100%); }
}
@-webkit-keyframes example1 {
0% { -webkit-transform: translateX(100%); }
100% { -webkit-transform: translateX(-100%); }
}
@keyframes example1 {
0% {
-moz-transform: translateX(100%); /* Firefox bug fix */
-webkit-transform: translateX(100%); /* Firefox bug fix */
transform: translateX(100%);
}
100% {
-moz-transform: translateX(-100%); /* Firefox bug fix */
-webkit-transform: translateX(-100%); /* Firefox bug fix */
transform: translateX(-100%);
}
}
</style>
The Practice of Computing Using Python (3rd Edition) 3rd Edition by William F. Punch (Author), Richard Enbody (Author), ISBN-13: 978-0134379760, © 2017. Chapter 5.
![]() |
---|
Karma Bus |
\begin{equation} f(c) = c * 1.8 + 32.0 \end{equation}
#
#
# Imagine a lot of statements
f = c * 1.8 + 32.0
#
# in a ln a lot of programs
#
#
f = c * 1.8 + 32.0
#
#
temp_f = temp_c * (212-32)/100 + 32
#
#
# Copyright 2017, 2013, 2011 Pearson Education, Inc., W.F. Punch & R.J.Enbody
# Temperature conversion
def celsius_to_fahrenheit(celsius_float):
""" Convert Celsius to Fahrenheit."""
return celsius_float * 1.8 + 32
freezing_c = 0
freezing_f = celsius_to_fahrenheit(freezing_c)
print("The Fahrenheit water freezing temperature is ", freezing_f)
I may not be able to tell you the correct way to do things. But, I know a lot of mistakes to avoid.
![]() |
---|
Mistakes |
![]() |
---|
Function Definition |
# Copyright 2017, 2013, 2011 Pearson Education, Inc., W.F. Punch & R.J.Enbody
# Conversion program
def celsius_to_fahrenheit(celsius_float):
""" Convert Celsius to Fahrenheit."""
return celsius_float * 1.8 + 32
import math
test = [727.7, 1086.5, 1091.0, 1361.3, 1490.5, 1956.1]
def compute_mu(data):
total = 0
count = len(data)
for i in range(0,count):
total += data[i]
result = total/count
return result
mu = compute_mu(test)
print("Mu = ", mu)
# The function needs/uses mu, but mu is not a parameter.
# Big mistake.
def compute_sigma(data):
total = 0
for n in data:
total += (mu - n)**2
result = math.sqrt(total/(len(data)-1))
return result
sigma = compute_sigma(test)
print("Sigma = ", sigma)
Anti-patterns: Don't be "that guy."
"An anti-pattern is a common response (solution) to a recurring problem that is usually ineffective and risks being highly counterproductive"
![]() |
---|
Don't be "that guy." |
![]() |
---|
Levenshtein Distance |
def generate_transposes(word):
result = []
# This was NOT that that hard to write, but ...
# is not easy to understand and I should have a comment or two,
for i in range(0,len(word)-1):
l = word[:i]
c1 = word[i]
c2 = word[i+1]
r = word[i+2:]
n = l + c2 + c1 + r
result.append(n)
return result
bad_word = "muose"
possible_words = generate_transposes(bad_word)
print("Possible words are: ", possible_words)
![]() |
---|
CPU, RAM, Files |
![]() |
---|
Input/Output (I/O) |
![]() |
---|
Memory Access Times |
f = open("AAPL.csv","r")
s = f.readline()
print("The first line of text is \n" + s)
print("The first five characters of the next line of text are \n")
s = f.readline(5)
print(s)
print("The 10 characters after that are + \n")
s = f.readline(10)
print(s)
f.close()
print("File 'paths' follow the conventions of the OS directory/folder structure.")
f = open("/Users/donaldferguson/Documents/GitHub/e1006s18/Notebooks/AAPL.csv","r")
print("The first 5 lines are:")
for i in range(0,5):
print(f.readline())
f.close()
print("File 'paths' follow the conventions of the OS directory/folder structure.")
f = open("/Users/donaldferguson/Documents/GitHub/e1006s18/Notebooks/AAPL.csv","r")
print("The first 5 lines are just line any other strings:")
file_lines = []
for i in range(0,5):
file_lines.append(f.readline())
print("file_lines is a 'list' of strings, which are sequences of text. The list =")
print(file_lines)
print("")
print("And let's do some string stuff ...")
s = file_lines[0]
print("The first string backwards is", s[-1::-1])
f.close()
![]() |
---|
File Open Modes |
import time
f = open("/users/donaldferguson/tmp/message.txt","a")
t = time.gmtime()
t = time.asctime(t)
print("Writing the current time to the text file: ",t,file=f)
f.close()
import json
courses = []
courses.append({ "title" : "Introduction to Databases", "number": "W4111" })
courses.append({ "title" : "Introduction to Computing for Engineers and Applied Scientists", "number": "E1006" })
print(json.dumps(courses, indent=4))
import time
t = time.gmtime()
t = time.asctime(t)
s = { "output_time": t, "courses": courses}
f = open("/Users/donaldferguson/tmp/some.json","a")
print(json.dumps(s, indent=4),file=f)
f.close()
From Punch and Enbody, chpt. 6.
![]() |
---|
Weinberg's Second Law |
![]() |
---|
Error Names (Punch and Enbody) |
< DFF-Non-Textbook-Digression >
< /DFF-Non-Textbook-Digression >
%%HTML
<!-- HTML -->
<div style="height:85px; color:red" class="example1">
<h3>Rule 7: All input is evil until proven otherwise.</h3>
</div>
![]() |
---|
Exceptions Form 1 |
# This program allows a user to input the radius on a circle.
# We want to teach the formula to young children. So, we only
# allow the radius to be an integer.
# Almost every program you write will use "programs" others have written.
# Your successful programs will become programs that others use.
# Any non-trivial program requires a team. The team members assemble
# the solution from individual subcomponents they build.
# The subcomponents and reusable parts are called modules.
import math # We just imported our first module.
# Programs, like mathematical functions, are only useful if they
# operate on many user provided inputs. To start, we will get the input from
# the "command line."
done = False
error_count = 0
self_destruct = False
while not done:
try:
if self_destruct:
x = 1 / 0
# Print a prompt asking for the radius.
# Set a variable to the input value.
radius_str = input('Enter the radius of a circle: ')
# We are going to do 'math' on the input. So, we should
# covert it to an Integer.
radius_int = int(radius_str)
# The circumfrence is 2 times pi time the radius.
# The area is pi * r squared.
circumference = 2 * math.pi * radius_int
area = math.pi * (radius_int ** 2)
# Python conventions do not like lines that are too long.
# \ means that we will continue the command on the next line.
print ("The cirumference is:",circumference, \
", and the area is:",area)
done = True
except ValueError as e1:
error_count = error_count + 1
if (error_count == 1):
print("\nInvalid type. You need to enter an integer.")
elif error_count == 2:
print("\nInvalid type. What part of integer did you not understand?")
elif error_count == 3:
print("\nSeriously? I cannot work like this. I am a professional.")
print("Next time you do this I divide by 0!")
else:
print("\n Self-destruct sequence started.")
self_destruct = True
except Exception as e:
print("\nException = ", e)
print("Self-destruct complete.")
break
finally:
print('\n Finally always called.')
done = False
while not done:
try:
fn = input("Please enter a file name?")
print("You entered ...", fn)
f = open(fn,"r")
print("\nReading file.")
for s in f:
print("A line = ",s)
print("Done")
done = True
except FileNotFoundError:
print("File not found. I will be patient.")
except Exception:
print("Something else happened.")
break
%%HTML
<!-- HTML -->
<div style="height:100px; color:red" class="example1">
<h3 class="example1">Reminder: Rules do far</h3>
</div>
<div style="height:100px; color:red" class="example1">
<h3 class="example1">Think before you program!</h3>
</div>
<div style="height:200px; color:green" class="example1">
<h3 style="color:green;" class="example1">A program is a human-readable essay on problem solving that also happens to execute on a computer.</h3>
</div>
<div style="height:150px; color:red" class="example1">
<h3 class="example1">The best way to improve your programming and problem solving skills is to practice!</h3>
</div>
<div style="height:150px; color:red" class="example1">
<h3 style="color:red;" class="example1">A foolish consistency is the hobgoblin of little minds</h3>
</div>
<div style="height:100px; color:red" class="example1">
<h3 style="color:red;" class="example1">Test your code, often and thoroughly</h3>
</div>
<div style="height:150px; color:red" class="example1">
<h3 style="color:red;" class="example1">If it was hard to write, it is probably hard to read. Add a comment.</h3>
</div>
<div style="height:150px; color:red" class="example1">
<h3 style="color:red;" class="example1">All input is evil, unless proven otherwise.</h3>
</div>
<div style="height:100px; color:red" class="example1">
<h3 style="color:blue;" class="example1">Don get's bored easily.'</h3>
</div>