branching and enumeration -...

34
Branching and Enumeration 1 Location of Modules where does Python find its modules? 2 Booleans and Branching computing logical expressions computing truth tables with Sage if, else, and elif 3 Timing Python Code try-except costs more than if-else 4 Recursive Problem Solving enumerating all letter combinations MCS 507 Lecture 8 Mathematical, Statistical and Scientific Software Jan Verschelde, 14 September 2012 Scientific Software (MCS 507) Branching and Enumeration 14 Sep 2012 1 / 34

Upload: dinhtuyen

Post on 23-Aug-2018

220 views

Category:

Documents


0 download

TRANSCRIPT

Branching and Enumeration

1 Location of Moduleswhere does Python find its modules?

2 Booleans and Branchingcomputing logical expressionscomputing truth tables with Sageif, else, and elif

3 Timing Python Codetry-except costs more than if-else

4 Recursive Problem Solvingenumerating all letter combinations

MCS 507 Lecture 8Mathematical, Statistical and Scientific Software

Jan Verschelde, 14 September 2012

Scientific Software (MCS 507) Branching and Enumeration 14 Sep 2012 1 / 34

Branching and Enumeration

1 Location of Moduleswhere does Python find its modules?

2 Booleans and Branchingcomputing logical expressionscomputing truth tables with Sageif, else, and elif

3 Timing Python Codetry-except costs more than if-else

4 Recursive Problem Solvingenumerating all letter combinations

Scientific Software (MCS 507) Branching and Enumeration 14 Sep 2012 2 / 34

the module search path

The module sys exports the module search pathas the dynamic object path.

>>> import sys>>> sys.path[’’, ’...’, ...]

sys.path[0] is the script directory, or ’’.

The order of the directories in the list returned by sys.pathdetermines the order in which Python searches for modules to import.

Scientific Software (MCS 507) Branching and Enumeration 14 Sep 2012 3 / 34

my math module

def test():print "This is my math module!"

if __name__=="__main__": test()

If we save the code above as math.py in the current directory wherewe call the python interpreter, then:

>>> import math>>> math.test()This is my math module!>> from math import cosTraceback (most recent call last):File "<stdin>", line 1, in <module>

ImportError: cannot import name cos

Scientific Software (MCS 507) Branching and Enumeration 14 Sep 2012 4 / 34

doing an “un-import”What if we want to import the right math module?

>>> import math>>> math.test()This is my math module!>>> import sys>>> sys.modules[’math’]<module ’math’ from ’math.py’>>>> del sys.modules[’math’]

modules is a dictionary of loaded modules, removing path[0]:

>>> sys.path = sys.path[1:]>>> from math import cos>>> cos(3)-0.9899924966004454

Scientific Software (MCS 507) Branching and Enumeration 14 Sep 2012 5 / 34

Branching and Enumeration

1 Location of Moduleswhere does Python find its modules?

2 Booleans and Branchingcomputing logical expressionscomputing truth tables with Sageif, else, and elif

3 Timing Python Codetry-except costs more than if-else

4 Recursive Problem Solvingenumerating all letter combinations

Scientific Software (MCS 507) Branching and Enumeration 14 Sep 2012 6 / 34

booleans

Type bool is another elementary data type:

>>> type(True)<type ’bool’>

Although True is 1 and False is 0:

>>> ’%d’ % True’1’>>> ’%d’ % False’0’

Printing booleans as strings:

>>> str(True)’True’>>> ’%s’ % True’True’

Scientific Software (MCS 507) Branching and Enumeration 14 Sep 2012 7 / 34

comparison operators

The outcome of a comparison is True or False:

>>> 1 < 7True>>> 1 >= 7False

The comparison operators:

== x == y is equal?!= or <> x != y not equal?< x < y less than?> x > y greater than?<= x <= y less or equal?>= x >= y greater or equal?

Scientific Software (MCS 507) Branching and Enumeration 14 Sep 2012 8 / 34

boolean operators

>>> x = 3>>> (x > 0) and (x < 10)True>>> (x < 0) or (x < 5)True>>> not (x < 0)True

The brackets are not needed.

and x and y both True?or x or y is one True?not not x is False?

Scientific Software (MCS 507) Branching and Enumeration 14 Sep 2012 9 / 34

Branching and Enumeration

1 Location of Moduleswhere does Python find its modules?

2 Booleans and Branchingcomputing logical expressionscomputing truth tables with Sageif, else, and elif

3 Timing Python Codetry-except costs more than if-else

4 Recursive Problem Solvingenumerating all letter combinations

Scientific Software (MCS 507) Branching and Enumeration 14 Sep 2012 10 / 34

truth tables in Sage

sage: logic = SymbolicLogic()sage: s = logic.statement("a&b")

Instead of and, use the & operator.

sage: t = logic.truthtable(s)sage: logic.print_table(t)

a | b | value |------------------------False | False | False |False | True | False |True | False | False |True | True | True |

Scientific Software (MCS 507) Branching and Enumeration 14 Sep 2012 11 / 34

the or operation

Sage session continued...

sage: s = logic.statement("a|b")

Instead of or, use the | operator.

sage: logic.print_table(logic.truthtable(s))a | b | value |------------------------False | False | False |False | True | True |True | False | True |True | True | True |

Scientific Software (MCS 507) Branching and Enumeration 14 Sep 2012 12 / 34

the not operation

Sage session continued...

sage: s = logic.statement("!a")

Instead of not, use the ! operator.

sage: t = logic.truthtable(s)sage: logic.print_table(t)a | value |----------------False | True |True | False |

Scientific Software (MCS 507) Branching and Enumeration 14 Sep 2012 13 / 34

proving De Morgan’s Law

The first law of De Morgan:

not (( not x ) or ( not y )) = x and y

Sage session continued ...

sage: law = ’!((!x)|(!y))’sage: s = logic.statement(law)sage: logic.print_table(t)x | y | value |------------------------False | False | False |False | True | False |True | False | False |True | True | True |

We recognize the truth table for x and y.

Scientific Software (MCS 507) Branching and Enumeration 14 Sep 2012 14 / 34

Branching and Enumeration

1 Location of Moduleswhere does Python find its modules?

2 Booleans and Branchingcomputing logical expressionscomputing truth tables with Sageif, else, and elif

3 Timing Python Codetry-except costs more than if-else

4 Recursive Problem Solvingenumerating all letter combinations

Scientific Software (MCS 507) Branching and Enumeration 14 Sep 2012 15 / 34

the if statement

The syntax of the if:

if < condition >:< statements when condition is True >

All statements to be executed only if the condition is true must bepreceded by the right intendations!

Suppose we want to print the ’+’ for positive numbers.

With an if we could do it as follows:

if x > 0: if x > 0:print ’+’ print ’+’print x print x

Only the second one works correctly for all x.

Scientific Software (MCS 507) Branching and Enumeration 14 Sep 2012 16 / 34

the if else statement

The syntax of the if else:

if < condition >:< statements when condition is True >

else:< statements when condition is False >

Printing the absolute value of a number:

if x < 0:print -x

else:print x

Scientific Software (MCS 507) Branching and Enumeration 14 Sep 2012 17 / 34

the elif statement

The grade for a course is represented by a letter.We compute the grade along a scale.

n = input(’Enter your number : ’)if n >= 90:

grade = ’A’elif n >= 80:

grade = ’B’elif n >= 70:

grade = ’C’elif n >= 60:

grade = ’D’else:

grade = ’F’print ’Your grade is ’ + grade + ’.’

Scientific Software (MCS 507) Branching and Enumeration 14 Sep 2012 18 / 34

Branching and Enumeration

1 Location of Moduleswhere does Python find its modules?

2 Booleans and Branchingcomputing logical expressionscomputing truth tables with Sageif, else, and elif

3 Timing Python Codetry-except costs more than if-else

4 Recursive Problem Solvingenumerating all letter combinations

Scientific Software (MCS 507) Branching and Enumeration 14 Sep 2012 19 / 34

cost of exception handlers

Exception handlers cost more than a regular conditions.

Rule: reserve exceptions for exceptional situations.

Let us try to test this rule on a simple case.

Computational experiment: repeated division.

for i in range(0,n):p = random.randint(-1,+1)q = random.randint(0,1)r = p/q

50% chance that q is zero

Scientific Software (MCS 507) Branching and Enumeration 14 Sep 2012 20 / 34

handling division by zero

Executing the division r = p/q.Count number of times q is zero.Using if-else statement:

if q != 0:r = p/q

else:cnt = cnt + 1

Using try-except statement:

try:r = p/q

except:cnt = cnt + 1

Claim: try-except costs more.

Scientific Software (MCS 507) Branching and Enumeration 14 Sep 2012 21 / 34

timing Python code

import time

starttime = time.clock()

< code to be timed >

stoptime = time.clock()

elapsed = stoptime - starttime

print ’elapsed time: %.2f seconds’ % elapsed

Replace < code to be timed > by a function call.

Scientific Software (MCS 507) Branching and Enumeration 14 Sep 2012 22 / 34

the function ifelse

def ifelse(n):"""Does n divisions of p by q,checks first if q is zero."""cnt = 0for i in range(0,n):

p = randint(-1,1)q = randint(0,1)if q != 0:

r = p/qelse:

cnt = cnt + 1print ’#divisions by zero :’, cnt

Scientific Software (MCS 507) Branching and Enumeration 14 Sep 2012 23 / 34

the function tryexcept

def tryexcept(n):"""Does n divisions of p by q,treats zero q as exception."""cnt = 0for i in range(0,n):

p = randint(-1,1)q = randint(0,1)try:

r = p/qexcept:

cnt = cnt + 1print ’#divisions by zero :’, cnt

Scientific Software (MCS 507) Branching and Enumeration 14 Sep 2012 24 / 34

the main program

def main():"""Compares the efficiency of if-else withthe try-except to avoid division by zero."""import timen = 1000000seed(2) # same sequence of random numbersstarttime = time.clock()ifelse(n)stoptime = time.clock()elapsed = stoptime - starttimeprint ’if-else: %.2f seconds’ % elapsedseed(2) # same sequence of random numbersstarttime = time.clock()tryexcept(n)stoptime = time.clock()elapsed = stoptime - starttimeprint ’try-except: %.2f seconds’ % elapsed

Scientific Software (MCS 507) Branching and Enumeration 14 Sep 2012 25 / 34

running time_iftry

on a MacBook 2.26 Ghz Intel Core 2 Duo

$ python time_iftry.py#divisions by zero : 499586if-else: 5.37 seconds

#divisions by zero : 499586try-except: 6.24 seconds$

Conclusion: try-except costs more.

But then: 50% of cases is not exceptional.→ improper use of try-except

Scientific Software (MCS 507) Branching and Enumeration 14 Sep 2012 26 / 34

Branching and Enumeration

1 Location of Moduleswhere does Python find its modules?

2 Booleans and Branchingcomputing logical expressionscomputing truth tables with Sageif, else, and elif

3 Timing Python Codetry-except costs more than if-else

4 Recursive Problem Solvingenumerating all letter combinations

Scientific Software (MCS 507) Branching and Enumeration 14 Sep 2012 27 / 34

enumeration to solve problems

Consider the following problem:

given are three lists of letters,

print all three letter words, using the given lists:the k-th letter in each word comes from the k-th list.

The number of words printed equals the product of the length of thelists.

E.g., let A = [’b’,’c’,’d’], B = [’a’,’e’,’u’], and C =[’d’,’p’], the script will print

bad bap bed bep bud bupcad cap ced cep cud cupdad dap ded dep dud dup

Scientific Software (MCS 507) Branching and Enumeration 14 Sep 2012 28 / 34

solving the enumeration problem

To solve the enumeration, observe:

The k-th character in each word that is printedis taken from the k-th list of letters.

We add characters to the current wordand k indicates the position in that word.

⇒ k is a control parameter for the recursion

Denote by n the length of the printed word.

If k = n, then we print the current word;otherwise, let c be the i-th character of list k

1 c is added to the current word; and2 we make a recursive call for k + 1.

Scientific Software (MCS 507) Branching and Enumeration 14 Sep 2012 29 / 34

enumwords.py

A = [’b’,’c’,’d’]; B = [’a’,’e’,’u’]; C = [’d’,’p’]

def enumwords(k,L,accu):"""Prints all words of length len(L), accumulatingin accu, choosing the k-th letter from L[k].In the first call, take 0 for k and "" for accu."""if(k >= len(L)):

print accuelse:

for i in xrange(len(L[k])):enumwords(k+1,L,accu+L[k][i])

enumwords(0,[A,B,C],"")

Scientific Software (MCS 507) Branching and Enumeration 14 Sep 2012 30 / 34

using the module itertools

The module itertools helps to create and use iterators.

To enumerate 3-letter words:

A = [’b’,’c’,’d’]; B = [’a’,’e’,’u’]; C = [’d’,’p’]

from itertools import productp = product(A,B,C)L = [p.next() for i in xrange(len(A)*len(B)*len(C))]print L

Scientific Software (MCS 507) Branching and Enumeration 14 Sep 2012 31 / 34

enumerating indices

The binary expansions of i in for i in range(7):

000 001 010 011 100 101 110 111

If a bit is an index, then this corresponds to enumerating all 3-letterwords with two choices for each letter.

Packing a knapsack with 3 objects: 0 means leave object out, 1 meanstake object in knapsack.

The knapsack problem: every object has a value and a weight.Keeping the weight below a threshold value, optimize the value of theknapsack.

Scientific Software (MCS 507) Branching and Enumeration 14 Sep 2012 32 / 34

Summary + Exercises

Recursive is a powerful problem solving technique.

Exercises:1 We once stated that xrange is more efficient than range. Setup

an experiment to verify this claim.For which dimensions is the difference significant?

2 Write a script that prompts the user for a number n and that thenprints all sublists of range(n).

3 Consider the problem of the previous exercise and explore theSage documentation on combinatorics.Can you solve the previous exercise faster with the tools Sage hasto offer?

Scientific Software (MCS 507) Branching and Enumeration 14 Sep 2012 33 / 34

more exercises

4 Give code for a Python program that asks the user for a logicalexpression (valid Python) in a string and a tuple of variables thatoccur in the expression. The program prints the truth table for theexpression.

5 The nth Fibonacci number Fn is defined for n ≥ 2 asFn = Fn−1 + Fn−2 and F0 = 0, F1 = 1. Write two Python functionsto compute Fn: one recursively and the other one withoutrecursion. Which function will be most efficient? Explain why.

The second homework is due on Friday 21 September, at 10AM:solve exercises 1 and 3 of Lecture 4; exercises 4 and 5 of Lecture 5;exercises 1, 2 and 5 of Lecture 6; exercises 1, 2, and 4 of Lecture 7.

Scientific Software (MCS 507) Branching and Enumeration 14 Sep 2012 34 / 34