510 likes | 661 Views
LING 408/508: Computational Techniques for Linguists. Lecture 5 8/29/2012. Outline. Booleans and logical operators Comparison operators Conditionals While loops Short assignment #4 Long assignment #1. Boolean data type. Name of datatype is bool Only two possible values: True False
E N D
LING 408/508: Computational Techniques for Linguists Lecture 5 8/29/2012
Outline • Booleans and logical operators • Comparison operators • Conditionals • While loops • Short assignment #4 • Long assignment #1
Boolean data type • Name of datatype is bool • Only two possible values: • True • False • Example: >>> b = True >>> b True
Logical operators: and, or, not • Binary operators: and, or • Take two arguments and produce a Boolean as the result • Syntax: A and B • Syntax: A or B • Unary operator: not • Takes one argument and produces a Boolean as the result • Syntax: not A
Rules of combination in Boolean logic • Example • Let A be the proposition “It is sunny” • Let B be the proposition “It is hot” • Suppose A = True, and B = True • What is the truth value of “It is sunny and it is hot”? • Represent “It is sunny and it is hot” as A and B • A and B is True • Suppose A = True, and B = False • What is the truth value of “It is sunny and it is hot”? • A and B is False
Truth tables • Suppose that A and B are Booleans. • These truth tables tell you the value of A and B, A or B, and not A. • A and B is True when both A and B are True, and False otherwise • A or B is True when either A or B is True, or both are True. • not A changes the value of A to its opposite.
Truth tables for complex logical expressions • Atomic (individual) variables in leftmost columns • Final expression in rightmost column • Other columns list ***all*** intermediate expressions created in the computation of the truth values for the final expression
and, or, not >>> True and False False >>> True or False True >>> not True False >>> not (not True) # = not False = True True >>> True and not False True >>> (True or False) or (False and True) True
Short-circuited evaluation >>> True or True or True or True or True or True or True or True or True or True or True or True or True or True or True or True or True or True or True or True or True or True or True or True or True or True or True or True or True or True True • Short-circuited evaluation: the first expression is True and is followed by or, so the rest of the expression doesn’t need to be evaluated
Demonstrate short-circuited evaluation >>> def left(): print('in left') return True >>> def right(): print('in right') return True >>> left() or right() in left True
Logical equivalence • Two boolean expressions are equivalent if they evaluate to the same result for all possible combinations of values of the individual variables • Consequence: can be used interchangeably in a program • For example, not not A is equivalent to A
De Morgan’s laws • These pairs of statements that are logically equivalent by De Morgan’s laws: 1. not (A and B) not A or not B 2. not (A or B) not A and not B
Demonstration of logical equivalence of not (A and B) and (not A) or (not B) For all possible combinations of values of A and B, not (A and B) and (not A) or (not B) have the same values
Built-in functions all and any >>> all([True, True, True]) True >>> all([False, False, False]) False >>> all([False, True, False]) False >>> any([True, False, False]) True >>> any([False, False, False]) False
Outline • Booleans and logical operators • Comparison operators • Conditionals • While loops • Short assignment #4 • Long assignment #1
Apply comparison operators to integers==, !=, >, <, >=, <= >>> 5 == 3 # test for equality False >>> 5 != 3 # test for inequality True >>> 5 > 3 # greater than, etc. True >>> 5 < 3 False >>> 5 >= 3 True >>> 5 <= 3 False
Comparison of lists: compares successive elements recursively >>> [1,2,3] == [1,2,3] True >>> [1,2,3] < [1,2,4] True >>> [1,2,[5,[8]]] < [1,2,[5,[7]]] # recursive False
== and = • Don’t confuse the two == is the equality operator = is the assignment operator • Example >>> a = 3 >>> b = 3 >>> a == b True >>> a == 4 False
Test whether an integer is even • An integer is even if it is divisible by 2 • i.e., the remainder after division is 0 • Use modulus operator (returns remainder after division) >>> a = 6 >>> a%2 == 0 True >>> b = 7 >>> b%2 1 >>> b%2 == 0 False
is operator for mutables >>> x = [1,2,3] >>> y = [1,2,3] >>> x == y # both lists have same values True >>> x is y # they don’t refer to the same list False >>> z = x # z refers to same memory location as x >>> x is z True
is operator for immutables >>> a = 3 >>> b = 3 >>> a == b # a and b have the same values True >>> a is b # a and b refer to same memory location True
Outline • Booleans and logical operators • Comparison operators • Conditionals • While loops • Short assignment #4 • Long assignment #1
Control flow • Control flow: order of execution of code • Standard order in Python: top to bottom • The execution of code can be made to be dependent upon particular conditions • Control flow in Python: • Conditional statement: if/elif/else • Loops: • while loops • for loops • List comprehensions
Conditional statement: if/elif/else • Syntax: (parentheses denote optionality) if <boolean>: # only one <statements> (elif <boolean>: # zero or more <statements>) (else: # at most one <statements>)
Flow chart for if/else statement if <boolean>: <block1 statements> else: <block2 statements> <rest of program>
Examples • if True: print('hello') else: print('bye') • a = 3 if a==4: # a==4 evaluates to a Boolean print('hello') # else block is optional • a = 3 if a==4: print('hello') elif a==5: # can have any number of elifs print('yes') else: print('bye')
Nested if statements and indentation if a: if b: print('yes') # executes if both else: # a and b are True if c: print('no') # execute if else: # a is False and c is True print('maybe')
Equivalent code if a: if b: print('yes') else: if c: print('no') else: print('maybe') if a and b: print('yes') elif c: print('no') else: print('maybe')
Boolean values of other types • Other types are converted to booleans in appropriate contexts >>> # can write on 1 line if one statement >>> if 1: print('hello') hello >>> if 0: print('hello') >>> if []: print('hello') # non-empty list >>> if [0]: print('hello') # evaluates as True hello >>> if [[]]: print('hello') hello
Outline • Booleans and logical operators • Comparison operators • Conditionals • While loops • Short assignment #4 • Long assignment #1
Loops • Used for repeated execution of code • Python has: • while loops • for loops • List comprehensions
Syntax of basic while loop,and flowchart while <boolean>: <statements> <rest of program>
Example i = 1 while i <= 5: print(i) i += 1 # Output: # 1 # 2 # 3 # 4 # 5
Example, step by step i = 1 while i <= 5: print(i) i += 1 condition Iterationii <= 5 actions 1 1 True print(1), i += 1 2 2 True print(2), i += 1 3 3 True print(3), i += 1 4 4 True print(4), i += 1 5 5 True print(5), i += 1 6 6 False exit loop
Components of a loop i = 1 while i <= 5: print(i) i += 1 • The variable i is called the loop counter • i <= 5 is the loop test • i += 1 is the increment statement
Infinite loop i = 1 while i <= 5: print(i) # i += 1 # infinite loop # prints 1 repeatedly # because value of i never changes
Example: factorial • Definition of factorial: n! = n * (n-1) * … * 1 • Example: 5! = 5 * 4 * 3 * 2 * 1 = 120 def factorial(n): # fac is initialized to 1 # after loop, fac will equal n! fac = 1 while n > 1: fac *= n n -= 1 return fac
def factorial(n): # fac is initialized to 1, # but after loop, fac will equal n! fac = 1 while n > 1: fac *= n n -= 1 return fac # let’s call the function factorial(5) condition Iterationn n > 1 action 1 5 True fac *= 5 fac is 5, n -= 1 2 4 True fac *= 4 fac is 20, n -= 1 3 3 True fac *= 3 fac is 60, n -= 1 4 2 True fac *= 2 fac is 120, n -= 1 5 1 False return fac, which is 120
Example: sum of a list L = [1, 2, 3, 4, 5] list_sum = 0 i = 0 while i < len(L): list_sum += L[i] i += 1
Example: construct a new list based on contents of another list • doubled_list(L): returns a new list whose values are that of L, multiplied by 2. (Assumes that L contains integers or floats) def doubled_list(L): doubled = [] i = 0 while i < len(L): doubled.append(L[i]*2) i += 1 return doubled
Nested loops • You can put a loop inside another loop • Standard names for loop counter variables: • Outer loop: i • Inner loop: j • If there’s another inner loop: k • The initial value of an inner loop counter is usually dependent upon an enclosing outer loop counter
Example: nested loops i = 0 while i < 4: j = i + 1 while j < 5: print(j, end=' ') # print space at end j += 1 # (default prints newline) print() # print newline here i += 1 # Output: # 1 2 3 4 # 2 3 4 # 3 4 # 4
Outer loop i = 0 while i < 4: j = i + 1 while j < 5: print(j, end=' ') j += 1 print() i += 1 • There are 4 iterations of the outer loop • In successive iterations, i takes values of 0, 1, 2, and 3
Inner loop i = 0 while i < 4: j = i + 1 while j < 5: print(j, end=' ') j += 1 print() i += 1 • The initial value for loop counter j is determined by the value of i • Examples: • when i is 0, j is initialized to 1 • when i is 2, j is initialized to 3 • In the inner loop, j increases; it terminates when j reaches 5
Values of i and j over all iterations i = 0 while i < 4: j = i + 1 while j < 5: print(j, end=' ') j += 1 print() i += 1 Outer loopInner loop i = 0 j = 1 j = 2 j = 3 j = 4 i = 1 j = 2 j = 3 j = 4 i = 2 j = 3 j = 4 i = 3 j = 4
Print statements • Putting a comma after a print statement suppresses printing of the newline character • Do this to continue printing on the current line • The example prints a newline after each inner loop i = 0 while i < 4: j = i + 1 while j < 5: print(j, end=' ') j += 1 print() i += 1
Output OuterInnerAction i = 0 j = 1 print(1,end=' ') j = 2 print(2,end=' ') j = 3 print(3,end=' ') j = 4 print(4,end=' ') print() i = 1 j = 2 print(2,end=' ') j = 3 print(3,end=' ') j = 4 print(4,end=' ') print() i = 2 j = 3 print(3,end=' ') j = 4 print(4,end=' ') print() i = 3 j = 4 print(4,end=' ') print() i = 0 while i < 4: j = i + 1 while j < 5: print(j, end=' ') j += 1 print() i += 1 # Output: # 1 2 3 4 # 2 3 4 # 3 4 # 4
Outline • Booleans and logical operators • Comparison operators • Conditionals • While loops • Short assignment #4 • Long assignment #1
Due 8/31 • Produce a truth table for not ( (A or C) and not (B and not A) ) Note that there are 3 atomic variables; if each can be either True or False, think about how many possible combinations of truth values are there for all 3 • Following the format of the example on slide 46, show the values of i and j and the result of print at each step of computation def f(L): i = len(L) while i >= 1: j = i- 1 while j >= 0: print(L[j:i], end=' ') j -= 1 print() i -= 1 f([1,2,3,4,5])
Outline • Booleans and logical operators • Comparison operators • Conditionals • While loops • Short assignment #4 • Long assignment #1