Download True

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Mathematics of radio engineering wikipedia , lookup

Law of large numbers wikipedia , lookup

Turing's proof wikipedia , lookup

Elementary mathematics wikipedia , lookup

Proofs of Fermat's little theorem wikipedia , lookup

Transcript
Acknowledgments
•
Many of the slides l use were created by Dr. Chuck
Severance, the author of our book.
•
You’ll typically recognize them by their black
backgrounds .
•
They are Copyright 2010–2014 Charles R. Severance
and are made available under a Creative Commons
Attribution 4.0 License.
•
Many of the slides I use were created by Dr. Jeremy
Abramson of USC/ISI. He simply gave them to me to use
in this class.
•
Many of the slides I use were created by me.
3
More About == (Equality) and is
>>> x = 2
>>> x = [1, 2]
>>> y = 2
>>> y = [1, 2]
>>> x is y
>>> x is y
True
False
>>> x == y
>>> x == y
True
True
>>> y = x
>>> x is y
True
>>> x[0] = 'a'
>>> y
['a', 2]
4
Conversion Matrix
meter
centimeter
yard
foot
meter
1
100
1.09
3.28
centimeter
0.01
1
0.011
0.033
yard
0.92
91.44
1
3
foot
0.3
30.48
0.33
1
conversionMatrix = [[1,100,1.09,3.28],[0.01,1,0.011,0.033],\
[0.91,91.44,1,3],[0.3,30.48,0.33,1]]
index = {'meter': 0, 'centimeter': 1, 'yard': 2, 'foot': 3}
conversionMatrix[index[unit1]][index[unit2]]
7
Iterations, Loops, String
Operations
8
Repeated Steps
n=5
No
n>0?
Yes
Program:
print n
n = n -1
n = 5
while n > 0 :
print n
n = n – 1
print 'Blastoff!'
print n
print 'Blastoff'
Output:
5
4
3
2
1
Blastoff!
0
Loops (repeated steps) have iteration variables that change
each time through a loop. Often these iteration variables go
through a sequence of numbers.
9
A Simple While Statement
n=5
while n>0:
print n
n=n-1
print ‘Blastoff!’
print n
•
More formally, here is the flow of execution for a while statement:
1. Evaluate the condition, yielding True or False.
2. If the condition is False, exit the while statement and continue
execution at the next statement.
3. If the condition is True, execute the body and then go back to
step 1.
10
n=5
No
An Infinite Loop
Yes
n>0?
print 'Lather'
n = 5
while n > 0 :
print 'Lather’
print 'Rinse'
print 'Dry off!'
print 'Rinse'
print 'Dry off!'
What is wrong with this loop?
11
n=0
No
Another Loop
Yes
n>0?
print 'Lather'
n = 0
while n > 0 :
print 'Lather'
print 'Rinse'
print 'Dry off!'
print 'Rinse'
print 'Dry off!'
What does this loop do?
12
•
Sometimes it’s more convenient to determine when
to exit the while loop in its body, as opposed to by
checking a condition
•
For that case, we have the break statement
13
Breaking Out of a Loop
• The break statement ends the current loop and jumps to the
statement immediately following the loop
• It is like a loop test that can happen anywhere in the body of the
loop
while True:
line = raw_input('> ')
if line == 'done' :
break
print line
print 'Done!'
14
> hello there
hello there
> finished
finished
> done
Done!
Breaking Out of a Loop
• The break statement ends the current loop and jumps to the
statement immediately following the loop
• It is like a loop test that can happen anywhere in the body of the
loop
while True:
line = raw_input('> ')
if line == 'done' :
break
print line
print 'Done!'
15
> hello there
hello there
> finished
finished
> done
Done!
Finishing an Iteration with continue
The continue statement ends the current iteration and jumps to
the top of the loop and starts the next iteration
while True:
line = raw_input('> ')
if line[0] == '#' :
continue
if line == 'done' :
break
print line
print 'Done!'
16
> hello there
hello there
> # don't print this
> print this!
print this!
> done
Done!
Wait!
•
What does this condition mean?
line[0] == ‘#’
•
A line of text is treated in some respects like a list of
characters, each of which can be referred to by its
index
•
This is true of all strings
myName = ‘Yigal Arens’
myName[5] == <what?>
•
But assignment, e. g., myName[5] = ‘x’ is NOT
legal
17
Finishing an Iteration with continue
The continue statement ends the current iteration and jumps
to the top of the loop and starts the next iteration
while True:
line = raw_input('> ')
if line[0] == '#' :
continue
if line == 'done' :
break
print line
print 'Done!'
18
> hello there
hello there
> # don't print this
> print this!
print this!
> done
Done!
No
True ?
while True:
line = raw_input('> ')
if line[0] == '#' :
continue
if line == 'done' :
break
print line
print 'Done!'
Yes
....
continue
...
print 'Done'
19
Indefinite Loop
•
A while loop is an indefinite loop, because it keeps
on iterating an indefinite number of times, until its
logical condition becomes False.
•
Sometimes we want a loop to iterate a specific
number of times
20
Definite Loops
• Quite often we have a list of items of the lines in a file - effectively a
finite set of things
• We can write a loop to run the loop once for each of the items in a
set using the Python for construct
• These loops are called “definite loops” because they execute an
exact number of times
• We say that “definite loops iterate through the members of a set”
21
A Simple Definite Loop
for i in [5, 4, 3, 2, 1] :
print i
print 'Blastoff!'
22
5
4
3
2
1
Blastoff!
A Definite Loop with Strings
friends = ['Joseph', 'Glenn', 'Sally']
for friend in friends :
print 'Happy New Year:', friend
print 'Done!'
23
Happy New Year: Joseph
Happy New Year: Glenn
Happy New Year: Sally
Done!
Let’s Look More Carefully
A Simple Definite Loop
Yes
Done?
No
Move i ahead
for i in [5, 4, 3, 2, 1] :
print i
print 'Blastoff!'
print i
print 'Blast off!'
5
4
3
2
1
Blastoff!
Definite loops (for loops) have explicit iteration variables
that change each time through a loop. These iteration
variables move through the sequence or set.
24
Looking at In...
• The iteration variable
“iterates” through the
sequence (ordered set)
• The block (body) of code is
executed once for each
value in the sequence
Iteration variable
Five-element sequence
for i in [5, 4, 3, 2, 1] :
print i
• The iteration variable moves
through all of the values in
the sequence
25
Yes
No
Done?
• The iteration variable “iterates”
through the sequence (ordered
set)
Move i ahead
print i
• The block (body) of code is
executed once for each value in
the sequence
• The iteration variable moves
through all of the values in the
sequence
for i in [5, 4, 3, 2, 1] :
print i
26
i=5
Yes
print i
No
Done?
Move i ahead
i=4
print i
print i
i=3
print i
i=2
for i in [5, 4, 3, 2, 1] :
print i
print i
i=1
print i
27
Making “smart” loops
The trick is “knowing” something
about the whole loop when you are
stuck writing code that only sees
one entry at a time
Set some variables to initial
values
for thing in data:
Look for something or
do something to each
entry separately,
updating a variable
Look at the variables
28
Example: Find Largest Number in a List
Containing Positive Numbers
numbers = [14, 3, 2, 25, 8, 10]
•
How would you find the largest number?
•
Remember:
•
•
Think of some variable to set initially
•
Go through the numbers, changing that variable if
necessary
•
Check the variable’s final result
What would that variable be?
29
Which Is the Largest Number?
14
3
2
25
30
8
10
Example: Find Largest Number in a List
Containing Positive Numbers
numbers = [14, 3, 2, 25, 8, 10]
largestSoFar = -1
for num in numbers:
if num > largestSoFar:
largestSoFar = num
print ‘Largest number was’, largestSoFar
31
Example: Find Average of Numbers in a
List
numbers = [14, 3, 2, 25, 8, 10]
•
How would you find the average?
•
Remember:
•
•
Think of some variable(s) to set initially
•
Go through the numbers, changing that
variable(s) if necessary
•
Check the variable(s) final result
What would those variables be?
32
Example: Find Average of Numbers in a
List
numbers = [14, 3, 2, 25, 8, 10]
count = 0
sumSoFar = 0
for num in numbers:
count = count + 1
sumSoFar = sumSoFar + num
average = float(sumSoFar) / count
print ‘There were’, count, ‘numbers’
print ‘Their average was’, average
33
String Operations
34
Strings Recap
•
A string literal uses double or single quotes
>>> string1 = ‘Bob’
•
The operator + on strings concatenates them
>>> print string1 + ‘12’ + ‘Alice’
Bob12Alice
•
A string that contains numbers is still a string
•
Can convert the right string to a number with int() and float()
>>> string2 = ‘1.5’
>>> string3 = ‘100’
>>> float(string2)
1.5
>>> int(string3)
100
>>> float(string3)
100.0
35
Strings Recap
•
We prefer to read input as a string, then parse it
and convert it as needed
•
This gives us more control over bad user input
•
But raw input numbers must be converted!
>>> num = raw_input(‘Enter number: ‘)
Enter number: 13
>>> print int(num) / 2
6
•
What would have happened had I not used int?
36
Looking Inside Strings
•
We can look at any character in a string using an index in square
brackets, e. g., str[5]
>>> myName = ‘Yigal Arens’
>>> print myName[2]
<what do I get?>
•
The index can be computed
>>> x = 2
>>> print myName[x ** 2]
<what do I get?>
•
What happens if I try the following?
>>> print myName[x ** 5]
<what do I get?>
37
Strings Have Length
• There is a built-in function len that
gives us the length of a string
b a
0 1
n a n a
2 3 4 5
>>> fruit = 'banana'
>>> print len(fruit)
6
38
Len Function
>>> fruit = 'banana'
>>> x = len(fruit)
>>> print x
6
'banana'
(a string)
A function is some stored
code that we use. A
function takes some input
and produces an output.
len()
function
6
(a number)
Guido wrote this code
What is fruit[len(fruit)] ?
39
Looping Through Strings
• Using a while statement and
an iteration variable, and the
len function, we can
construct a loop to look at
each of the letters in a string
individually
fruit = 'banana'
index = 0
while index < len(fruit):
letter = fruit[index]
print index, letter
index = index + 1
40
0b
1a
2n
3a
4n
5a
Looping Through Strings
• A definite loop using a for
statement is much more
elegant
• The iteration variable is
completely taken care of by
the for loop
fruit = 'banana'
for letter in fruit :
print letter
index = 0
while index < len(fruit) :
letter = fruit[index]
print letter
index = index + 1
41
b
a
n
a
n
a
Looking deeper into in
• The iteration variable
“iterates” through the
sequence (ordered set)
• The block (body) of code is
executed once for each
value in the sequence
Iteration variable
Six-character string
for letter in 'banana' :
print letter
• The iteration variable moves
through all of the values in
the sequence
42
Slicing Strings
M o n t y
P y t h o n
0 1 2 3 4 5 6 7 8 9 10 11
• We can also look at any
continuous section of a string
using a colon operator
>>> s = 'Monty Python'
>>> print s[0:4]
Mont
>>> print s[6:7]
P
>>> print s[6:20]
Python
• The second number is one
beyond the end of the slice “up to but not including”
• If the second number is
beyond the end of the string, it
stops at the end
Slicing Strings
43
Slicing Strings
M o n t y
P y t h o n
0 1 2 3 4 5 6 7 8 9 10 11
>>> s = 'Monty Python'
>>> print s[:2]
Mo
>>> print s[8:]
thon
>>> print s[:]
Monty Python
• If we leave off the first
number or the last number
of the slice, it is assumed to
be the beginning or end of
the string respectively
Slicing Strings
44
Using in as a logical Operator
• The in keyword can also be
>>> fruit = 'banana'
>>> 'n' in fruit
True
>>> 'm' in fruit
False
>>> 'nan' in fruit
True
>>> if 'a' in fruit :
...
print 'Found it!'
...
Found it!
>>>
used to check to see if one
string is “in” another string
• The in expression is a
logical expression that
returns True or False and
can be used in an if
statement
45
String Comparison
if word == 'banana':
print 'All right, bananas.'
if word <
print
elif word
print
else:
print
'banana':
'Your word,' + word + ', comes before banana.'
> 'banana':
'Your word,' + word + ', comes after banana.'
'All right, bananas.'
➜ Let’s try it
46
Libraries of Functions/Methods
•
There are libraries of functions (AKA “methods”)
associated with certain types of objects in Python
•
Some are built-in, and later we’ll learn how to define
our own
•
The string library has many useful functions
•
We call them by appending the function to a string
variable, with a ‘.’ between them
•
(This is an example of a more general facility we’ll
learn about later.)
47
String Library
• Python has a number of string
functions which are in the string
library
>>> greet
>>> zap =
>>> print
hello bob
>>> print
Hello Bob
>>> print
hi there
>>>
• These functions are already built into
every string - we invoke them by
appending the function to the string
variable
• These functions do not modify the
original string, instead they return a
new string that has been altered
48
= 'Hello Bob'
greet.lower()
zap
greet
'Hi There'.lower()
String Methods
•
capitalize, center, count, decode, encode, endswith, expandtabs,
find, format, index, isalnum, isalpha, isdigit, islower, isspace,
istitle, isupper, join, ljust, lower, lstrip, partition, replace, rfind,
rindex, rjust, rpartition, rsplit, rstrip, split, splitlines, startswith,
strip, swapcase, title, translate, upper, zfill
•
A Few Examples
•
Or execute the Python command
>>> dir(‘string’)
The string functions/methods are defined here:
https://docs.python.org/2/library/stdtypes.html#string-methods
str.capitalize()
Return a copy of the string with its first character capitalized and the rest lowercased.
For 8-bit strings, this method is locale-dependent.
str.center(width[, fillchar])
Return centered in a string of length width. Padding is done using the specified fillchar (default is
a space).
str.count(sub[, start[, end]])
Return the number of non-overlapping occurrences of substring sub in the range [start, end].
Optional arguments start and end are interpreted as in slice notation.
49
Particularly Useful String Functions
str.capitalize()
str.center(width[, fillchar])
str.endswith(suffix[, start[, end]])
str.find(sub[, start[, end]])
str.lstrip([chars])
str.replace(old, new[, count])
str.lower()
str.rstrip([chars])
str.strip([chars])
str.upper()
50
How to Extract A Substring
•
This is what a typical first line in an email looks like
From [email protected] Mon Sep
•
5 15:24:10 2016
Suppose I would like to extract the host the
message was sent from
>>> line = ‘From [email protected] Mon Sep
51
5 15:24:10 2016’
Extracting A Substring
•
This is what a typical first line in an email looks like
From [email protected] Mon Sep
•
5 15:24:10 2016
Suppose I would like to extract the host the
message was sent from
>>> line = ‘From [email protected] Mon Sep
>>> atpos = line.find(‘@‘)
>>> sppos = line.find(‘ ‘, atpos)
>>> hostname = line[atpos + 1 : sppos]
52
5 15:24:10 2016’