Sunday, September 28, 2014

Week#3

First of all, I would like to appreciate about this course is designed well to make us work and understand the concept / logic deeply and thoroughly. Without tutorials, I could get puzzled with this course.

In week-3 lectures & tutorials, I learned how to interpret English words to the symbols that computer scientists use. The tutorial this week made the paradox (or myth) I had much clearer.

I think I'm good this week with CSC165.

Now... I want to note about a mathematics' Law - De Margan's Law. This is sometimes critical when it comes to Python programming.

For example, (this is from my previous course in summer - CSC108), if there are two events in Python Class variables and we want to check if the two events overlap or not. Here is the code for checking the overlap (recall this is from my previous course in summer).


1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class Event:    
    """A new calendar event."""

    def __init__(self, start_time, end_time, event_name):
        """ (Event, int, int, str) -> NoneType

        Precondition: 0 <= start_time < end_time <= 23
        
        Initialize a new event that starts at start_time, ends at end_time,
        and is named event_name.

        >>> e = Event(12, 13, 'Lunch')
        >>> e.start_time
        12
        >>> e.end_time
        13
        >>> e.name
        'Lunch'
        """
        
        self.start_time = start_time
        self.end_time = end_time
        self.name = event_name

    def overlaps(self, other):
        """ (Event, Event) -> bool

        Return True iff this event overlaps with event other.

        >>> e1 = Event(6, 7, 'Run')
        >>> e2 = Event(0, 7, 'Sleep')
        >>> e1.overlaps(e2)
        True
        """
        
        return not ((self.end_time <= other.start_time) or \
        (other.end_time <= self.start_time))

When I was doing this exercise, I remember I put:


1
return (self.end_time <= other.start_time) and (other.end_time <= self.start_time)

in the def overlaps function. It is literally correct in English. However, Python does not check the right hand side of  and if the left hand side fails.

A and B
For example in this statement, if A is false, then this whole statement is false whether or not B is true. Therefore, Python program will never get to B when A fails.

This line needs to be checked both ways from the right to left and from the left to right. In order to do this, De Morgan's Law kicks in.
A and B <=> Not (A or B)
This is beautiful! This is very simple, but quite important in programming language.



No comments:

Post a Comment