Title: Aucun titre de diapositive
1(No Transcript)
2(No Transcript)
3(No Transcript)
4Computation
- Anything a computer can do.
- Most programming languages are Turing complete.
That is, they are expressive enough to describe
any computation that is possible. - A programming language must interface to all the
hardware devices and software packages that we
need to use.
5Machine-Readable
- The language must have a fixed syntax, so that a
machine can read (parse) programs. - The language must have a fixed semantics, so the
computer knows what a program means and can
execute it.
6Human-Understandable
- This goal becomes much harder for larger programs
because of the challenge of controlling
complexity. - Our main tool for controlling complexity is
abstraction. - Abstraction means emphasizing the essential
aspects of a task, and hiding irrelevant details. - Good programming languages include special
features for supporting abstraction.
7Human-Computer Gap
- Human is interested in modeling the real world.
More interested in what computer should do than
how. - Computer can only manipulate data if it is
sequences of zeroes and ones. - The instructions that it understands are all
low-level how instructions like Copy the
contents of memory location 0xFF04 to memory
location 0xFF08.
8High-level languages
- High-level languages bridge this gap by providing
a higher-level notation that can still be
executed by a computer. - Good libraries of abstractions can help to
further bridge the gap. - Some application-specific high-level languages
can bridge the gap completely for certain
application areas. Ex. spreadsheets, database
applications. - A good programming environment can help the human
programmer bridge the remaining gap more quickly,
with fewer mistakes and less pain.
9Programming LanguageGenerations
- First Generation Assembly languages.
- Second Generation Unstructured High-Level
Languages. Ex. FORTRAN. - Third Generation Structured High-level
languages. Ex. Algol, Pascal, C, Ada. - Fourth Generation Application-specific languages
for building database-oriented systems. - Fifth Generation Very high-level languages,
especially logic programming languages and other
declarative languages. Ex. Prolog.
10Declarative versus Imperative Languages
- Imperative Programming write down a sequence of
commands (imperatives). - Declarative Programming declare what results we
want and leave the programming language to figure
out how to produce them. - Declarative What
- Imperative How
11Problems
- The hope is that programs in declarative
languages will be shorter and simpler, because
they need not specify how results are computed. - However, the difficulty with declarative
programming languages is getting the programming
language to figure out a reasonably efficient
how by itself. - The more expressive the language is, the harder
this is.
12Examples
Consider a declarative language in which a
program is a set of equations, plus an expression
to be evaluated. Ex 1. Evaluate x, given x
y z 1 u 2 y z / u z 3 Ordering these
equations gives an imperative implementation. But
if we allow more expressive equations,
implementation is harder. Ex 2 x y z 1 u
2 u y z z 3 Ex 3 ( fact(0) 1
fact(n 1) n fact(n) )
13Four Computational Paradigms
- Imperative Program is a sequence of commands
(imperatives). - Object-Oriented Program is a set of interacting
objects. - Functional Program is a set of function
definitions. - Logic Program is a set of statements that
describe the desired results. - Many languages support several paradigms.
- The object-oriented style can be combined with
any of the other three. - But currently, most object-oriented languages are
imperative-based.
14More Esoteric Programming Languages
- Visual/graphical programming languages. Programs
represented as graphs or pictorially in some
other way. - Rule-based programming languages. Ex. Expert
systems. - Application-specific programming languages. Ex.
spreadsheets, macro languages, screen-painters.
15What Makes a Good Language?
- Human Criteria
- Learnable Is language easy to learn and
remember? - Writable Easy to write correct programs?
- Readable Easy to understand programs?
- Maintainable Easy to change programs?
- Computer Criteria
- Implementable Can language be implemented?
- Efficient Are programs translated and executed
fast enough? - Portable Is language available on most computers?
16(No Transcript)
17Contd
- Orthogonality
- Language constructs can be combined in any
meaningful way and should not interact in
unexpected ways. - Generality
- Have one general construct rather than several
specific one. Avoid restricting the ways
constructs can be used. - Preciseness.
- Is the language precisely defined? ANSI/ISO
standard? Does it have a formal semantics?
Validation suites?
18(No Transcript)
19Readability/Understandability
- Most of the learnability design goals help
readability. - Expressiveness can also improve readability if
the programmer has used it wisely Ex. use
abstraction mechanisms to build high-level
abstractions and map directly to
application-level concepts. - Documentation support. Documentation is essential
for understanding large programs. Most languages
allow comments. Some languages have better
support. - Language Environment. Ex. browsers,
cross-reference tools, pretty-printers.
20Maintainability
- In addition to the readability and writability
design goals, design goals that improve
maintainability include - Machine Independence. Ban or isolate
machine-specific features. - Modularity. Good modularity constructs allow one
part of a program to be changed without impacting
other parts.
21Some early languagesFortran (1954-1957)
- IBM FORmula TRANslating system for IBM 704
computer. - Strict instruction format. Loose typing.
- Major emphasis on compiler producing efficient
code. Emphasis on equation solving. - Became the major scientific/engineering
programming language. - Much evolution FORTRAN II, FORTRAN IV,
FORTRAN66, FORTRAN77, FORTRAN90.
22(No Transcript)
23Contd Algol60 (1958-1960)
- ALGOrithmic Language general expressive language
for describing algorithms. - Used widely in Europe, within academia in USA.
- Modern syntax defined using BNF, free-format,
structured statements, with begin/end pairs. - Type declarations required for all variables.
- Introduced recursion, call-by-name and
call-by-value. - Required stack-based runtime environment.
- Huge influence on later languages Pascal, C,
Modula-2, Ada, etc.
24(No Transcript)
25(No Transcript)
26Modern languages
- Pascal (1972) A small simple Algol-based language
for teaching. - Elegant data structuring records, arrays, files,
sets. - Slogan Algorithms Data Structures Programs.
- Became the most taught language in universities.
27Contd
- C (1972)
- Low-level language for writing an operating
system (UNIX). Can reference bits like an
assembly language. - Prolog (1972-1980)
- The first logic programming language.
- Efficient compilers only available in late 1980s
and 1990s. - Smalltalk (1972-1980)
- The first pure object-oriented language.
- Included a powerful interactive development
environment, with windowing system, menus and
mouse.
281980s languages
- Ada (1980-1983)
- Large and complex Pascal-like language, by U.S.
DoD. - Strengths include machine-independent
arithmetic, generic packages, concurrency and
exceptions. - Ada95 adds object-orientation.
- Modula-2 (1982)
- An improved Pascal with good abstraction
features. - C (1980-1990)
- C extended with object-orientation.
- A compromise language, to enable C compatibility.
- Currently, the most widely used object-oriented
language.
291990s Java
- In 1991 the WWW started and Java was designed at
Sun Microsystems. Its bytecode portability made
it useful for sending programs across the
internet. Browsers added Java interpreters. - Java quickly became popular as a general
programming language, in spite of its slowness,
because machines now fast/large enough.
Programmer time portability more important than
speed. - Safety
- Java traps all runtime errors properly.
- Bytecode verifier does many checks.
- Several semantics and correctness proofs for
parts of Java
30Important features
- Interoperability becomes more important
- Pure OO and logic languages are now practical.
- Efficient implementations are available.
- A smooth interface with the imperative world.
- We can have our declarative cake and eat it too!
312000s
- 2000 Microsoft proposes C and .net.
- 2002 Waikato University releases Starlog (logic
programming) - 2003 Microsoft releases Visual Haskell?
(visual, functional programming) - ? ????
32Procedural vs Declarativelanguages
- Procedural languages (code data in one program)
- Imperative languages (where assignment is
fundamental, as in C, Java, etc.) - Functional languages (most instructions are
functions, as in ML, LISP, XML, Haskell, Python,
etc.). - Declarative languages allow programmers to state
a problem without stating how to solve it. Data
defined separately from algorithms. Most
non-procedural languages are logic languages - Logic languages have syntax and semantics based
on some form of logic. For example, Prolog is
(partially) based on Horn clause logic, and OBJ
is based on equational logic. - SETL is based on set theory, which is not a form
of logic, so it is a non-logical and
non-procedural, declarative language.
33Various languages - OOP
- Object-oriented languages
- Cecil is a language that supports both untyped
programming and large-scale statically-typed
programming. - Dylan is a safe, strongly-typed, pure
object-oriented language that supports modules,
first-class functions - Python is interpreted and ideal for quick
prototypes, but with a nice module system, lots
of handy libraries, and almost purely
object-oriented. - Blue, Modula3, Oberon, Sather, Object Pascal -
Delphi - , Eiffel, TOM,
34Various languages Functional Programming
- Functional Programming
- Haskell is an elegant high-level language, with
fast compiled implementations plus an interpreter
(HUGS) that is good for development. - Python is a functional language for quick
proto-typing.
35Various languages Logic Programming
- Logic program
- Prolog is the most commonly known logic
programming language - Starlog research group, which is designing and
implementing a new pure logic-programming
language that is especially suited to reactive
and real-time programming. - Mercury is an elegant, pure, logic programming
language from Melbourne University. The fastest
logic programming language around.
36FUNCTIONS
x1
minus
x2
zero
x3
x4
plus
x5
function
range
domain
sign(x)
37Definition
- No ambiguity as to which range element a given
domain element is mapped to. - Functions are said to be well-defined or
deterministic - A function that applies to all elements of the
domain is called total function. - sign(x) minus if xlt0
- zero if x0
- plus if xgt0
- A function that applies to some elements of the
domain is a partial function. - sign(x) minus if xlt0
- plus if xgt0
38Terms
- x is called the formal parameter of the
function - 6 would be an actual parameter which is
applied to the function - For sign(6) we say that the expression
evaluates to plus - Function composition is the evaluation of an
expression for the evaluation of a function - max (4,3,7) max (max (4,3), 7 )
39Illustration
Then
If
composition
function
The composition can then be treated as one black
box because it gives a unique output value for
each input
40Referential Transparency
- Each expression gives a unique value which cannot
be evaluated differently by this part of the
program or by passing it to another part of the
program. - This makes the difference between imperative
programming and functional programming. - In imperative programming, a procedure can access
a global variable modify its value. - These dynamic changes are called side-effects.
Therefore, imperative languages are called
referentially opaque.
41Pascal Example
The first write evaluates to 5.
The second write evaluates to 4.
The value of the global variable is allowed to be
modified
This side effect, called destructive assignment,
can only occur in imperative languages.
42Variables in functional programming
- A variable IS NOT a place holder for different
values - Variables have values that cannot be modified.
- A program IS NOT a sequence of imperatives
describing HOW to solve a problem by modifying
variables. - A functional program describes WHAT is to be
computed according to a pre-defined function.
43PYTHON
- Python is extensible it is easy to add a new
built-in function or module to the interpreter,
either to perform critical operations at maximum
speed, or to link Python programs to libraries
that may only be available in binary form (such
as a vendor-specific graphics library). - You can link the Python interpreter into an
application written in C and use it as an
extension or command language for that
application. - The Python interpreter translates the source code
into temporary bytecode first and executed as a
script.
44Executing Python Code
- One way is to type python and then type a
command following the prompt gtgtgt to be
interpreted individually. - To exit Python type ctrl-Z in DOS. You can also
call a system library function to exit - import sys
- sys.exit()
- You can also type a Python program in a text file
and call it name.py and then execute it with
the command C\,gtpython name.py - index.html file in Docs folder is where you
can help. - Whitespaces at same indent determine blocks of
code. - In the IDLE environment you can create the file
in edit mode and then use run.
45Boolean Values Expressions
- A and B true if both A B are true
- A or B true if either A or B are true
- A B true if A equals B
- A ! B, A ltgt B true if A is not equal to B
- not B true if B is false
- Numbers are true if they are not equal to 0
- Collections (strings,) are true if not empty
- Variables are true if they reference a valid
object - NONE is a special value indicating an invalid
object
46Arithmetic on command line
gtgtgt 22 a comment on the same line as
code 4 gtgtgt This is a comment on a separate
line ... (50-56)/4 5 gtgtgt Integer division
returns the floor ... 7/3 2 gtgtgt 7/-3 -3 gtgtgt
15/4.0 3.75 gtgtgt 72 modulo operator
47Output with markers
- gtgtgt print 74
- 3
- gtgtgt print The answer is , 2312
- The answer is 35
- gtgtgt print The sum of d and d is d
(7,13,713) - The sum of 7 and 13 is 20
- Markers
- s string
- x hexadecimal number
- 0.2f real number with 2 digits after
decimal point - 4d pad number with leading spaces to have at
least 4 digits - 04d pad number with leading zeros to have at
least 4 digits - A trailing comma suppresses the carriage return
at the end of the print command.
48Variables
- Variables are the labels used to store data in
specific memory locations. - Variables are assigned a type by assignment
- gtgtgt x 6 x is now an integer
- You cannot mix certain types such as adding a
number to a string. - Character strings can be enclosed by simple
quotes, double quotes or a triple of double
quotes (to preserve the format) - gtgtgt print Single quotes
- Single quotes
- gtgtgt print Double quotes
- Double quotes
- To include an apostrophe or a quote, use a
backslash - gtgtgt print This isn\t it
- This isnt it
49Literals
- String literals can span multiple lines in
several ways. Continuation lines can be used,
with a backslash as the last character on the
line indicating that the next line is a logical
continuation of the line - hello "This is a rather long string
containing\n\ - several lines of text.\n\
- Note that whitespace at the beginning of the
line is\ - significant."
- We can also use the triple double quotes
- gtgtgt print ??? We can preserve
- the exact
- format ???
- We can preserve
- the exact
- format
50Assignments
As in C, the equal sign ("") is used to assign a
value to a variable gtgtgt width 20 gtgtgt height
59 gtgtgt width height 900 A value can be
assigned to several variables simultaneously
gtgtgt x y z 0 Assign zero to x, y and
z gtgtgt x 0 gtgtgt y 0 gtgtgt z 0 The right side is
evaluated first, then it is assigned to the left,
from left to right a, b b, ab
51String Operators
Strings can be concatenated (glued together) with
the operator gtgtgt word 'Help' er' gtgtgt
word 'Helper and repeated with gtgtgt 'lt'
word5 'gt' 'ltHelperHelperHelperHelperHelpergt'
52The variable _
In interactive mode, the last printed expression
is assigned to the variable _. This means that
when you are using Python as a desk calculator,it
is somewhat easier to continue calculations,for
example gtgtgt tax 12.5 / 100 gtgtgt price
100.50 gtgtgt price tax 12.5625 gtgtgt price
_ 113.0625 gtgtgt round(_, 2) 113.06 gtgtgt This
variable should be treated as read-only by the
user. Don't explicitly assign a value to it as
you would create an independent local variable
with the same name masking the built-in variable
with its magic behavior.
53Arrays
The first character of a string has subscript
(index) 0. There is no separate character type a
character is simply a string of size one.
Substrings can be specified with the slice
notation two indices separated by a colon.
Taking word Helper gtgtgt word4 e' gtgtgt
word02 'He' gtgtgt word24 'lp'
54Slices 1
Slice indices have useful defaults an omitted
first index defaults to zero, an omitted second
index defaults to the size of the string being
sliced. gtgtgt word2 The first two
characters 'He' gtgtgt word2 All but the
first two characters 'lper' Here's a useful
invariant of slice operations si si
equals s. gtgtgt word2 word2 'Helper' gtgtgt
word3 word3 'Helper'
55Slices 2
Indices may be negative numbers, to start
counting from the right. For example gtgtgt
word-1 The last character r' gtgtgt
word-2 The last-but-one character e' gtgtgt
word-2 The last two characters er' gtgtgt
word-2 All but the last two
characters 'Help'
56Collections Lists 1
Python knows a number of compound data types,
used to group together other values. The most
versatile is the list, which can be written as a
list of comma-separated values (items) between
square brackets. List items need not all have the
same type. gtgtgt a 'spam', 'eggs', 100,
1234 gtgtgt a 'spam', 'eggs', 100, 1234 Unlike
strings, which are immutable, it is possible to
change individual elements of a list, but it will
be a local assignment gtgtgt a 'spam', 'eggs',
100, 1234 gtgtgt a2 a2 23 'spam', 'eggs',
123, 1234
57Lists 2
Like string indices, list indices start at 0, and
lists can be sliced, concatenated gtgtgt
a0 'spam' gtgtgt a3 1234 gtgtgt a-2 100 gtgtgt
a1-1 second element from the right 'eggs',
100 gtgtgt a2 'bacon', 22 'spam', 'eggs',
'bacon', 4 gtgtgt 2a3 'Boe!' 'spam',
'eggs', 100, 'spam', 'eggs', 100, 'Boe!' The
built-in function len() also applies to lists
gtgtgt len(a) 8
58Lists 3
Assignment to slices is also possible, and this
can even change the size of the list gtgtgt
Replace some items ... a02 1, 12 gtgtgt
a 1, 12, 123, 1234 gtgtgt Remove some ...
a02 We can use the library function
d gtgtgt a 123, 1234 gtgtgt Insert some ...
a11 'bletch', 'xyzzy' gtgtgt a 123,
'bletch', 'xyzzy', 1234 gtgtgt a0 a
Insert (a copy of) itself at the beginning gtgtgt
a 123, 'bletch', 'xyzzy', 1234, 123, 'bletch',
'xyzzy', 1234 gtgtgt print a04 more
2 123, 'bletch', 'xyzzy', 1234, more, more
59Lists 4
It is possible to nest lists (create lists
containing other lists), for example gtgtgt q
2, 3 gtgtgt p 1, q, 4 gtgtgt len(p) 3 gtgtgt p 1,
2, 3, 4 gtgtgt p1 2, 3 gtgtgt p10 first
element of second list 2 gtgtgt p1.append('xtra')
append a library function gtgtgt p 1, 2, 3,
'xtra', 4 gtgtgt q 2, 3, 'xtra' This is very
useful to create tables and grids.
60Tuples Dictionaries
- Tuples are defined by parentheses and are
immutable, i.e they cannot be modified. - gtgtgt aTuple (2,4,6)
- They can be indexed
- gtgtgt aTuple1
- 4
- Dictionaries have keys and values. They are
initialized with braces, but you assign and read
values with square brackets - gtgtgt dict ??
- gtgtgt dictinteger A whole number
- gtgtgt print dictinteger
- A whole number
-
61Control statements - IF
gtgtgt x int(raw_input("Please enter an integer
")) gtgtgt if x lt 0 ... x 0 ... print
'Negative changed to zero' ... elif x 0 ...
print 'Zero' ... elif x 1 ... print
Positive' ... else ... print Error in
input' ...
62Control statements - FOR
Python's for statement iterates over the items of
any sequence (a list or a string), in the order
that they appear in the sequence. For example
gtgtgt Measure some strings ... a 'cat',
'window', 'defenestrate' gtgtgt for x in a ...
print x, len(x) ... cat 3 window 6 defenestrate
12 gtgtgt for i in range(1,13) print d x 12
d (i, i12)
63Range 1
If you do need to iterate over a sequence of
numbers, the built-in function range() comes in
handy. It generates lists containing arithmetic
progressions gtgtgt range(10) 0, 1, 2, 3, 4, 5,
6, 7, 8, 9 The given end point is never part of
the generated list range(10) generates a list of
10 values, exactly the legal indices for items of
a sequence of length 10. It is possible to let
the range start at another number, or to specify
a different increment (even negative sometimes
this is called the step') gtgtgt range(5, 10) 5,
6, 7, 8, 9 gtgtgt range(0, 10, 3) 0, 3, 6, 9 gtgtgt
range(-10, -100, -30) -10, -40, -70
64Range 2
To iterate over the indices of a list, combine
range() and len() as follows gtgtgt a 'Mary',
'had', 'a', 'little', 'lamb' gtgtgt for i in
range(len(a)) ... print i, ai ... 0
Mary 1 had 2 a 3 little 4 lamb
65Break, continue, else
Loop statements may have an else clause it is
executed when the loop terminates or when the
condition becomes false but not when the loop is
terminated by a break statement. This is
exemplified by the following loop, which searches
for prime numbers gtgtgt for n in range(2,
10) ... for x in range(2, n) ... if
n x 0 ... print n, 'equals', x,
'', n/x ... break ... else ...
loop fell through without finding a
factor ... print n, 'is a prime
number' ...
66While loop
- gtgtgt j 1
- gtgtgt while j lt 12
- gtgtgt print d x 12 d (j, j12)
- gtgtgt j j 1
- What does it print?
67Getting input from the user
- To collect the characters typed at the keyboard
and present them as a string you use raw_input. - gtgtgt print raw_input(Type your initials )
- Type your initials
- To save the name
- gtgtgt name raw_input(Type your name )
- Type your name Marc
- gtgtgt print Hi, s. name
- Hi, Marc.
- To collect input as numbers use input.
- gtgtgt age input(How old are you? )
- How old are you? 18
- gtgtgt print If you are 3d or older, you may
proceed. age - If you are 18 or older, you may proceed.
68Functions 1
gtgtgt def fib(n) write Fibonacci series up to n
a, b 0, 1 while b lt n
print b, a, b b, ab gtgtgt
Now call the function we just defined ...
fib(2000) 1 1 2 3 5 8 13 21 34 55 89 144 233 377
610 987 1597
69Functions 2
To return a list of the numbers of the Fibonacci
series, instead of printing it gtgtgt def fib2(n)
return Fibonacci series ... result
... a, b 0, 1 ... while b lt n ...
result.append(b) ... a, b b,
ab ... return result ... gtgtgt f100
fib2(100) name it gtgtgt f100
write the result 1, 1, 2, 3, 5, 8, 13, 21, 34,
55, 89 The return statement returns with a
value from a function. return without an
expression argument returns None. Falling off
the end of a procedure also returns None.
70Imported Function
- gtgtgt c
- gtgtgt s a short string
- gtgtgt import string
- gtgtgt words string.split(s,c)
- The function splits the string into words using
as a separator. - Library functions can be used in 2 ways
- gtgtgt import sys
- gtgtgt sys.exit()
- Or
- gtgtgt from sys import
- gtgtgt exit()
71Default argument values
The most useful form is to specify a default
value for one or more arguments. This creates a
function that can be called with fewer arguments
than it is defined def ask_ok(prompt, retries4,
complaint'Yes or no, please!') while 1
ok raw_input(prompt) if ok in ('y',
'ye', 'yes') return 1 if ok in ('n',
'no', 'nop', 'nope') return 0 retries
retries - 1 if retries lt 0 raise
IOError, 'refusenik user' print
complaint This function can be called either like
this ask_ok('Do you really want to quit?') or
like this ask_ok('OK to overwrite the file?',
2).
72Evaluation of default value
The default value is evaluated only once. This
makes a difference when the default is a mutable
object such as a list or dictionary. For example,
the following function accumulates the arguments
passed to it on subsequent calls def f(a,
L) L.append(a) return L print f(1)
will print 1 print f(2) will print
1,2 print f(3) will print 1,2,3 If you
don't want the default to be shared between
subsequent calls, you can write the function like
this instead def f(a, LNone) if L is
None L L.append(a)
return L
73Local parameter value changes
- Values of parameters changed in a function will
not be changed in the calling module. - gtgtgt def incr(n)
- n n1
- gtgtgt i2
- gtgtgt print incr(i)
- 2
- In order to change the content of a list but
not the list itself we do the following - gtgtgt def parrot(L)
- L.append(squaw)
- gtgtgt P
- gtgtgt parrot(p)
- gtgtgt print P
- squaw
74Funct. prog. properties
- The execution of a function introduces a new
symbol table used for the local variables of the
function. More precisely, all variable
assignments in a function store the value in the
local symbol table whereas variable references
first look in the local symbol table, then in the
global symbol table, and then in the table of
built-in names. Thus, global variables cannot be
directly assigned a value within a function
(unless named in a global statement), although
they may be referenced. - The actual parameters (arguments) to a function
call are introduced in the local symbol table of
the called function when it is called thus,
arguments are passed using call by value (where
the value is always a variable reference to the
value). When a function calls another function, a
new local symbol table is created for that call.
75Keyword argument
Functions can also be called using keyword
arguments of the form "keyword value". For
instance, the following function def
parrot(voltage, state'a stiff', action'voom',
type'Norwegian Blue') print "-- This parrot
wouldn't", action, print "if you put",
voltage, "Volts through it." print "-- Lovely
plumage, the", type print "-- It's", state,
"!" could be called in any of the following ways
parrot(1000) parrot(action 'VOOOOOM', voltage
1000000) parrot('a thousand', state 'pushing
up the daisies') parrot('a million', 'bereft of
life', 'jump')
76Functional programming tools
"filter(function, sequence)" returns a
sub-sequence of items from the sequence for which
function(item) is true. For example, to find some
numbers not divisible by 2 or 3 gtgtgt def f(x)
return x 2 ! 0 and x 3 ! 0 ... gtgtgt
filter(f, range(2, 25)) 5, 7, 11, 13, 17, 19,
23 "map(function, sequence)" calls
function(item) for each of the sequence's items
and returns a list of values. For example, to
compute some cubes gtgtgt def cube(x) return
xxx ... gtgtgt map(cube, range(1, 11)) 1, 8, 27,
64, 125, 216, 343, 512, 729, 1000
77Filter map
More than one sequence may be passed the
function must then have as many arguments as
there are sequences and is called with the
corresponding item from each sequence (or None if
some sequence is shorter than another). If None
is passed for the function, a function returning
its argument(s) is substituted. Combining these
two special cases, we see that "map(None, list1,
list2)" is a convenient way of turning a pair of
lists into a list of pairs. For example gtgtgt seq
range(8) gtgtgt def square(x) return xx ... gtgtgt
map(None, seq, map(square, seq)) (0, 0), (1, 1),
(2, 4), (3, 9), (4, 16), (5, 25), (6, 36), (7,
49)
78Modules 1
- If you quit from the Python interpreter and
enter it again, the definitions you have made
(functions and variables) are lost. Therefore, if
you want to write a somewhat longer program, you
are better off using a text editor to prepare the
input for the interpreter and running it with
that file as input instead. This is known as
creating a script. As your program gets longer,
you may want to split it into several files for
easier maintenance. You may also want to use a
handy function that you've written in several
programs without copying its definition into each
program. - To support this, Python has a way to put
definitions in a file and use them in a script or
in an interactive instance of the interpreter.
Such a file is called a module definitions from
a module can be imported into other modules or
into the main module.
79Modules 2
A module is a file whose name has the suffix .py
appended. Within a module, the module's name is
available as the value of the global variable
__name__. For instance, create a file called
fibo.py in the current directory containing the
following 2 functions def fib(n) write
Fibonacci series up to n a, b 0, 1
while b lt n print b, a, b b,
ab def fib2(n) return Fibonacci series up
to n result a, b 0, 1
while b lt n result.append(b)
a, b b, ab return result
80Module 3
Now enter the Python interpreter and import this
module gtgtgt import fibo gtgtgt fibo.fib(500) 1 1
2 3 5 8 13 21 34 55 89 144 233 377 6 gtgtgt
fibo.fib2(100) 1, 1, 2, 3, 5, 8, 13, 21, 34,
55, 89 gtgtgt fibo.__name__ 'fibo'
81Standard modules
Python comes with a library of standard modules.
Some modules are built into the interpreter
these provide access to operating system
primitives such as system calls, or for
efficiency. The variables sys.ps1 and sys.ps2
define the strings used as primary and secondary
prompts gtgtgt import sys gtgtgt sys.ps1 'gtgtgt ' gtgtgt
sys.ps2 '... ' gtgtgt sys.ps1 'Cgt ' These two
variables are only defined if the interpreter is
in interactive mode. The standard output file
can be referenced as sys.stdout.
82Reading writing files
open() returns a file object , and is most
commonly used with two arguments "open(filename,
mode)". gtgtgt fopen('/tmp/workfile', 'w') gtgtgt
print f ltopen file '/tmp/workfile', mode 'w' at
80a0960gt gtgtgt f.read() 'This is the entire
file.\n' The mode can be r - read w -
write r - read write a - append b -
binary f.readline() reads a single line from the
file
83Reading Writing Files 2
- inp open(myFile.txt, r)
- for line in inp.readlines()
- print line
- inp.close()
- For large files you might want to read each line
with readline, until the end of line_count - For binary files we add a b in the mode and use
read()
84Namespaces 1
- A namespace is a region, within a program, where
a name is valid. The name is local. The scope is
the accessible area of the namespace. - When variable names are global, one function can
modify a variable value without other functions
realizing it. This creates side-effects. - In Python, every module and every class creates
its own namespace. This makes Python a functional
language. - Python permits only 3 namespaces
- Local, within a class, function, or method
- Module, within a file
- Built-in, defined by Python
- To assign a value to a variable outside its
namespace, it must be declared as global
85Namespaces 2
Module namespace
A function will first look in in its local
namespace, then the module namespace, then the
built-in namespace.
Function namespace
Class namespace
Method namespace
If a local variable and a module variable of the
same name are used in a function, the local
variable value will mask the module one.
86Namespaces 3
- The global namespace for a module is created when
the module definition is read in normally,
module namespaces also last until the interpreter
quits. The statements executed by the top-level
invocation of the interpreter, either read from a
script file or interactively, are considered part
of a module called __main__, so they have their
own global namespace. - The built-in names actually also live in a
module this is called __builtin__. - The local namespace for a function is created
when the function is called, and deleted when the
function returns or raises an exception that is
not handled within the function. Recursive
invocations each have their own local namespace. - Name spaces are created at different moments and
have different lifetimes. The namespace
containing the built-in names is created when the
Python interpreter starts up, and is never
deleted.
87CLASSES
- The simplest form of class definition looks like
this - class ClassName
- ltstatement-1gt
- .
- .
- .
- ltstatement-Ngt
- Class definitions, like function definitions (def
statements) must be executed before they have any
effect. They are the only user-defined type in
Python. - When a class definition is entered, a new
namespace is created, and used as the local scope
-- thus, all assignments to local variables go
into this new namespace. In particular, function
definitions bind the name of the new function
here. - Objects are collections of data and the
functions (methods) that operate on that data. A
class is a collection of objects with identical
properties. - A class is a template for the objects of that
class.
88Class Object Example
- class Address
- def _init_(self,no,st,city,state,zip)
- self.number no
- self.street st
- self.city city
- self.state state
- self.zipCode zip
- We create an object instance of that class as
follows - Addr Address(10,Main St.,Clark,NY,12901)
- gtgtgt Print (Addr.number, Addr.street)
- 10 Main St.
89Class Instantiation 1
- Class instantiation creates a new instance of
the class and assigns this object to a local
variable. - The instantiation operation creates an empty
object. Many classes like to create objects in a
known initial state. Therefore a class may define
a special constructor method named __init__(),
like this - def __init__(self)
- self.data
- The __init__() method may have arguments for
greater flexibility. - The argument self indicates the object
instance.
90Data Attributes Methods
- Data attributes are the values given to the
arguments to form an object instance. - A method is a function that belongs to'' an
object. - If 2 objects of different classes share the same
message (method call) but have different method
implementation, we have polymorphism. - In Python, the term method is not unique to
class instances other object types can have
methods as well. For example, list objects have
methods called append, insert, remove, sort, and
so on.
91Example of polymorphism
- class Square
- def _init_(self,side)
- self.side side
- def calculateArea(self)
- return self.side2
- class Circle
- def _init_(self,side)
- self.radius radius
- def calculateArea(self)
- return math.pi(self.radius2)
- Now we can obtain the areas of various shapes
- list Circle(4), Square(10),
Circle(2),Square(4) - for shape in list
- print The area is , shape.calculateArea()
92Inheritance
- A class can inherit both attributes and methods
from a superclass. Thus neither need be implement
once again. - A subclass or object can override the attributes
or methods that it wants handled differently. - Thus, we can create a class Animal, a subclass
Cat and an object instance Tom. -
93Inheritance Example
class Animal(self,live,organs,covering) self.al
ive live self.organs organs self.cover
covering class Cat(Animal) def
attributes(cover,whiskers,tail) self.fur
cover self.whisk whiskers self.tail
tail Tom Cat(fur,whisk,no_tail) Tom is a cat
with no tail.
94PROLOG
- Prolog is based on First Order Predicate Logic
(FOPL) - It uses Horn clauses to represent sentences
- It is weakly typed
- Problems are described by facts rules stored in
a built in DB and queried - It provides an automatic search strategy
95Propositional logic
- Based on statements with truth values
- open(csc314) - csc314 is open
- Uses connectives ? (conjunction), ?
(disjunction), ? (implication), ? (equivalence),
? (negation) - open(csc314) ? meets(tr)
- csc314 is open meets on t,r
- prereq(csc217) ? poi
- prerequisite is csc217 or poi
96FOPL
- It permits relations between entities called
clauses - prereq(csc314,csc217)
- It allows variables
- man(x) ? mortal(x)
- It has quantifiers universal ? (for all),
existential ? (there exists) - ?x dog(x) ? animal(x)
- The x in dog(x) is free but the x in ?x
dog(x) is bound because all values for x in
domain are accounted for. - A formula with no free variables is a sentence.
97Prolog Syntax
- We might say NY has_capital Albany. This is in
infix form - Prolog uses clauses with prefix form
has_capital(ny,albany). - Constants (called atoms) usually start with lower
case letters - There is no space between the predicate and the
bracket
98Multiple Clauses
- A predicate is defined by a set of clauses ending
with a period - has(dog,tail)?has(dog,four_paws)?has(dog,two_ears
) - written in Prolog as
- has(dog, tail).
- has(dog, four_paws).
- has(dog, two_ears).
99Prolog constants
- A constant is an atom or a number
- A number is an integer or a real
- An atom can be
- A quoted item or string
- A word starting with a letter followed by a
letter, digit or underscore - A symbol ,-,,/,\, , lt,gt,,, ,,.,?,_at_,,,
- Special items ,, , ! ,
- A single quote within an atom must be duplicated
- All predicates must be constants but not numbers
100Rules
- The FOPL clause even(X) ? divisible_by_two(X) is
called a rule in Prolog. - Rules are in the form of non-unit clauses with a
head (then- true) and a body (if-true) - divisible_by_two(X)- even(X).
- X is a logical variable. Variables start with a
capital letter. - Note that the head is the goal, the body is the
condition or sub-goal, that is there is a
backward deduction or backward chaining. - Note that there is an implicit universal
quantifier ?X
101Logical variables scope
- In imperative languages, variables are space
holders, or a storage location that can contain
different values (ex X). - In Prolog, a logical variable cannot be
overwritten with a new value. They start with a
capital letter except for the anonymous variable,
the underscore. - Examples
- happy(X)- healthy(X)
- X always has the same value within this clause
- wise(X)- old(X)
- X always has the same value within this clause
- logical variable X is the same within the scope
of each clause.
102Conjunctive rules
- long(Board) ? wide(Board) ? large(Board)
FOPL - large(Board)- long(Board),
- wide(Board). Prolog
- The comma serves as conjunction
- This rule has 2 subgoals or conditions.
- Board is capitalized because it is a logical
variable. - The rule is implicitly universally qualified
103Disjunctive rules Functors
- (ripe(Apples)?red(Apples)) ? (ripe(Apples)?
yellow(Apples)) ? edible(Apples)
FOPL - edible(Apples)- ripe(Apples),red(Apples).
- edible(Apples)- ripe(Apples),green(Apples).
- Predicate edible, called a functor, is used in
multiple rules for a disjunction. - It is implicitly universally qualified.
- The arity of a predicate is the number of its
arguments. edible has arity 1 written as
edible/1
104 Answering queries
- A query ascertains the truth of a goal.
- Prolog starts execution by printing the prompt
?- and expects a query. - The user types a clause, finishing with a period,
and a carriage return. - Prolog returns yes or no.
105Declarative aspect of queries
A procedure that squares input numbers can give
rise to 4 different queries
Database square(X,XX)
Queries What is the square of ---? What number
has square ? What numbers are related by
square? Are 2 numbers related by square?
Database is generated by the program
square(X,XX)
106Queries from DB
Queries What is the square of 2? What number has
square 5? What numbers are related by
square? Are 2 numbers related by square?
?- square(2,X) ?- square(X,5) ?- square(X,Y) ?-
square(2,3)
107Example of query with multiple goals
myDB distance(mercury,36). distance(venus,67).
distance(earth,93) . distance(mars,141). distan
ce(jupiter,484). distance(saturn,886). distance
(uranus,1790). distance(neptune,2800). distance
(pluto,4600). satellites(uranus,5). satellites(
earth,1). satellites(saturn,9). atmosphere(ea
rth,_). supports_life(Planet)-
distance(Planet,93), atmosphere(Planet,_),
satellites(Planet,1).
?- supports_life(X). To answer the query Prolog
must satisfy the 3 sub-goals of the predicate.
108Conjunctive query
- To ask questions with more than one goal with use
commas - ?- satellite(X,_),atmosphere(X,_).
- Prolog will first match satellite(X,_) with
satellite(Uranus). - It then instantiates X to Uranus.
- X is now bound to Uranus, and Prolog will try
to unify atmosphere(Uranus,_) with a fact in
the DB. It fails. - Prolog then backtracks and instantiates X with
earth. - It then unifies atmosphere(earth) with
atmosphere(X,_). - Both goals succeed, so the query returns earth.
109Tree representation
disjunction red apples ? yellow apples
conjunction ripe apples ? yellow apples
110 Solving problems with searches
- If we have a database of family relationships we
can answer questions about the members relations
by doing a search in the DB. - To find Mary we can start at the root of the
family DB and look at all the roots children,
all their children, etc, until we find Mary.
Paul
Breadth-first search
111Example of Resolution
The system must contain a DB, or a file, with
facts rules.
Prolog does a search on the same predicate of
same arity, then tries to match constant
parameters or substitute a logical variable to
find a goal that is true. It keeps a resolution
table to eliminate the wrong matches and to
return yes for the right match.
woman(jean). DB clause
woman(jane). current goal
? failure
?? no substitution
112Example of Unification binding of variables
?- happy(jean).
RESOLUTION TABLE
happy(Person)- woman(Person)
healthy(Person)
No
?
Bind Person --gt jean By unification
113Backward chaining in tree
happy(Person)
subgoals
woman(Person)
healthy(person)
Unify Person --gt jean
114When can we unify?
The clause likes(X,may) means that all Xs like
May. That is, everyone likes May.
In this case we can unify Tom, Jerry, Ann, Mary,
with X So the queries ?- likes(tom,may), ?-
likes(jerry,may), succeed.
However, the query ?- likes(bob,X) means Whom
does Bob like? So the textual X in the clause
is different from the textual X in the query.
We could naively unify the X in the clause with
May likes(bob,may) which is true since everyone
likes May.
But when we unify the X in the query with May
likes(bob,may) we are not answering the question
we were asking.
115Scope unification
The problem with the previous example is that of
the scope of X in run time.
When a clause contains a textual variable, its
scope is different from that of the textual
variable in the query, EVEN THOUGH THEY MIGHT BE
THE SAME VARIABLE.
To differentiate these variables, we usually use
X1 in the clause and X2, X3, in the queries.
116Planetary example 1
- ?- distance(Planet,93).
- Distance in query will be matched to distance in
DB. - The following matches will be attempted until a
positive match is obtained. The matching will
then stop. - distance(X,93) ? distance(mercury,36) ? no
- ? distance(venus,67) ? no ?
distance(earth,93) ? yes - Planet in query is now bound to earth in DB
117Planetary example 2
Given the following rule in the
DB supports_life(Planet)- distance(Planet,93)
, atmosphere(Planet,_), satellites(Planet,1).
The following query will generate the next
matching procedures ?- supports_life(X) Planet
in rules first subgoal will be bound to earth
in DB as in previous slide. So atmosphere(Planet,_
) in second subgoal will now be bound to
earth atmosphere(earth,_) ? atmosphere(earth,_)
? yes Now satellites(earth,1) in query will be
matched to same in DB. satellites(earth,1) ?
satellites(earth,1) ? yes The 3 sub-goals have
now be satisfied, so the main goal is satisfied.
118Getting multiple answers
Typing a semi-colon at the prompt forces the goal
to fail and causes Prolog to find alternate
answers ?- distance(X,Y). X mercury Y 36
? X venus Y 67 ?
119Contd
If you want alternate answers without being
prompted, use the predicate fail as the last
sub-goal in the rule find_all-
distance(X,Y), fail. But here Prolog returns
no because the fail sub-goal makes it retract its
finding each time. ?- find_all. distance(venus,6
7). fail() distance(earth,93). fail()
distance(pluto,4600). fail() No more matching
clauses. no
120Contd
To make fail_all succeed you need to add another
clause find_all- distance(X,Y), fail. fin
d_all. ?- find_all. yes
121Arithmetic computations
- To compute X 1 4 use the built-in is
predicate - Either X is 1 4
- Or is(X, (1,4))
- The operators can be
- , -, , /,
- gt, lt, gt, lt, (equality), / (inequality)
122Evaluation in Prolog
Y- 2 1. Results in Y being bound to 2
1, NOT 3 To evaluate 2 1 we must use the
predicate is Y is 2 1. Y is then bound
to 3. successor(X, Y)- Y is X 1. Will
bind the successor of X to Y.
?- successor(X,7) produces error because X is
not bound cannot be
evaluated ?- successor(3,X) succeeds because it
can bind X to 4 ?- successor(3,5) fails
correctly because 31 ? 5
123Example of rules that can infer
Rules how_far(Planet1,Planet2,Distance)- dista
nce(Planet1,X), distance(Planet2,X), Distance
is X Y, Distance gt 0. how_far(Planet1,Planet2
,Distance)- distance(Planet1,X), distance(Plane
t2,X), Distance is Y X.
124Uses of the Cut subgoal
- The cut (!) is one of the possible subgoals in a
predicate. It has 3 uses - When you execute only one clause of a predicate
to make it behave as an if-then-else construct - When you want to limit the programs search
through the DB - To handle exceptions
125Cut as an if-then-elseLimiting search thru DB
- myDB
- temp(81). thermostat(Action)-
- temp(69). temp(X),
- temp(75). action(X,Action),
- fail.
- action(X,Turn off heat)-
- X gt 80, !. thermostat(Action)-
- action(X,Turn on heat)- temp(X), !,
- X lt 70, !. action(X,Action),
- action(_,Take no action)- fail.
?- thermostat(69). Action Turn on heat With
only first thermostat rule
?- thermostat(X). Action Turn off heat With
only second thermostat rule
126Cut to handle exceptions
- In a study of livings things in a pond, algae is
an exception. Three samples are tested
sample(frog,turtle,salamander). study_sample-
sample(tadpole,catfish,algae). sample(X), sa
mple(turtle,salamander,trout). test_sam ple(X
), fail. test_sample(X)- study_sample.
member(algae,X), !, fail. test_sample(X)-
write(Valid sample X), nl.
?- study_samples. Valid sample
frog,turtle,salamander Valid sample
turtle,salamander,trout
127Contd
- The previous rules can be replaced by the
following one - test_samples(X)-
- not(member(algae,X)),
- write(Valid sample X), nl.
128Recursion in Prolog 1
- Here are some examples
- One of my ancestor is one of my parents or one of
their ancestors. - A string of characters is a single character or a
single character followed by a string of
characters. - A paragraph is a sentence or a sentence appended
to a paragraph. - To decouple a train, uncouple the first carriage
and then decouple the rest of the train.
129Recursion in Prolog 2
You talk about someone either if you know them or
if you know someone who talks about
them talks_about(A,B)- knows(A,B). talks_about
(P,R)- knows(P,Q), talks_about(Q,R). Recur
sion can be seen by subtrees in the same shape as
the main tree
130Example
- male(paul). parent(paul,monroe).
- male(monroe). parent(paul,susan).
- male(aaron). parent(barbara,monroe).
- female(susan). parent(barbara,susan).
- female(barbara). parent(monroe,aaron).
- mother(X,Y)- parent(X,Y), female(Y).
- father(X,Y)- parent(X,Y), male(Y).
- ancestor(X,Y)- parent(X,Y).
- ancestor(X,Z)- parent(X,Y), ancestor(Y,Z).
X monroe ? X susan ? X aaron ?
To find all Pauls ancestors ?-
ancestor(paul,X).
131Lists in Prolog
- Lists may contain atoms, terms or lists
- apples, oranges, bananas three atoms
- a,b,c,d,e,f six atoms
- an atom with no elements
- dog(fido), cat(tiger), bird(tweety) three
terms - fish(wanda), pear,peach, 1,2, 1,2,3
- a term, a list, a list of lists
- a,b,c is not the same as b,c,a
132List construction destruction by recursion
- Lists are made up of a HEAD with one element and
a TAIL with the rest of the list. - We can deconstruct a list thus
- X Y c,a,t then X contains c and Y
contains a,t - If V c,a,t then setting V c,a U will
give U t - To construct a list we add a head thus
- Z s Y results in Z containing s,a,t
- Z d,r Y results in Z containing d,r,a,t
- is the empty list and cannot be
deconstructed. It can be used to construct other
lists.
133Unifying Lists
- b,a,c c,a,b fails
- X a,b,c fails
- XY this, is, a, cat succeeds
- X,YZ a,b,c,d succeeds
- X a, Y b, Z c,d
- XY fails
- XY a,b,c,d succeeds
- X a,b,c, Y d
- XY a X a, Y succeeds
134Writing recursively
You write the first element of a list, and all
the others recursively print_list(). print_li
st(HT)- write(H), print_list(T). The
first clause handles the empty list. The second
clause handles all other lists, and fails at the
empty list, because cannot be
deconstructed. Built-in predicate nl/0 writes
each element on separate line.
135Using Head Tail recursively
To check if a list of elements contains all
digits all_digits(). all_digits(HeadTail)
- member(Head,0,1,2,3,4,5,6,7,8,9,), all_di
gits(Tail). To triple elements of a
list triple(,). triple(H1T1,H2T2)-
H2 is 3H1, triple(T1,T2). The goal
triple(1,2,3,4,X) would result in X1,4,9,16
136I/O in Prolog
To test the predicate double(X,Y) we can run a
test test- read(X), double(X,Y),
write(Y), nl. Or recursively test-
read(X), \(X-1), double(X,Y),
write(Y), nl, test.
137Character I/O
- get0(Char) accepts next character from
keyboard. - get(Char) accepts next character from keyboard
but skips spaces, tabs and newlines. - put(Char) writes a character to the terminal.
- tab(N) writes to terminal number of spaces
specified by N.