Principles of Computing (Part 2) -- week 1

6 篇文章 0 订阅
5 篇文章 0 订阅

1. The importance of Searching
  • 1D search
  • 2D search (space search)

2. Generators

Generators are a kind of iterator that are defined like functions. A generator function looks just like a regular function, except that it uses yield instead of return.

2.1. Get Next Element of Iterator an_iter.next( )

def foo():
    x = yield 1
    print 'Yielded:', x
    yield 2

bar = foo()
print bar.next()
print bar.next()

2.2. Get Next Element and Send Value to Generator a_gen.send( )

def add1genf(n):
    while n != None:
        print 'Before:', n
        n = yield n + 1
        print 'After:', n

add1gen = add1genf(10)
print '---'
print add1gen.send('This first value is ignored.')
print '---'
print add1gen.send(3)
print '---'
print add1gen.send(17)

3. Stacks and Queues

Stack class (LIFO: Last in First out):
http://www.codeskulptor.org/#user39_KvzEKByK1u_0.py

Queue class (FIFO: First in First out):
http://www.codeskulptor.org/#poc_queue.py

4. Inheritance
# Simple inheritance

class Base:
    def hello(self):
        print "hello"

    def message(self, msg):
        print msg

class Sub(Base):
    def message(self, msg):
        print "sub:", msg

obj = Sub()
obj.hello()
obj.message("what's going to happen?")

baseobj = Base()
baseobj.hello()
baseobj.message("another message")

5. Grid Class

Grid Class:
http://www.codeskulptor.org/#poc_grid.py

6. Grid search (BFS)

Breadth-first search (BFS) is a search strategy that models the growth of a fire in which the search proceeds radially outward from the initial search locations.

Recording whether a cell has been visited can be done efficiently using a grid. The grid cells are initialized to EMPTY to indicate that the cells have not been visited. Each time a cell is visited, the corresponding entry in the grid is set to FULL .

At the start of the search, the queue boundary is initialized to contain one or more cells. The entries in the grid visited corresponding to these cells should also be set as FULL to indicate that these cells have been visited by the search. With that background, here is a high-level description of the search in English:

while boundary is not empty:
    current_cell  ←  dequeue boundary
    for all neighbors neighbor_cell of current_cell:
        if neighbor_cell is not in visited:
            add neighbor_cell to visited
            enqueue neighbor_cell onto boundary

Note that use of a queue in this search causes the search to be radial in nature. At any point in the search, breadth-first search process all of the cells on the current boundary of the search before processing any new cells added to the search boundary. Replacing the queue by a stack in BFS yields an entirely different kind of search strategy call depth=first search (DFS). During depth-first search, the search propagates outward in one preferred direction until it can no longer proceed in that direction.

example: wildfire
http://www.codeskulptor.org/#poc_wildfire_student.py

7. Mini-project # week 1 – Zombies Apocalypse
    """
    Student portion of Zombie Apocalypse mini-project
    """

    import random
    import poc_grid
    import poc_queue
    import poc_zombie_gui

    # global constants
    EMPTY = 0 
    FULL = 1
    FOUR_WAY = 0
    EIGHT_WAY = 1
    OBSTACLE = "obstacle"
    HUMAN = "human"
    ZOMBIE = "zombie"


    class Zombie(poc_grid.Grid):
        """
        Class for simulating zombie pursuit of human on grid with
        obstacles
        """

        def __init__(self, grid_height, grid_width, obstacle_list = None, 
                     zombie_list = None, human_list = None):
            """
            Create a simulation of given size with given obstacles,
            humans, and zombies
            """
            poc_grid.Grid.__init__(self, grid_height, grid_width)
            if obstacle_list != None:
                for cell in obstacle_list:
                    self.set_full(cell[0], cell[1])
            if zombie_list != None:
                self._zombie_list = list(zombie_list)
            else:
                self._zombie_list = []
            if human_list != None:
                self._human_list = list(human_list)  
            else:
                self._human_list = []

        def clear(self):
            """
            Set cells in obstacle grid to be empty
            Reset zombie and human lists to be empty
            """
            poc_grid.Grid.clear(self)
            self._zombie_list = []
            self._human_list = []

        def add_zombie(self, row, col):
            """
            Add zombie to the zombie list
            """
            self._zombie_list.append((row, col))

        def num_zombies(self):
            """
            Return number of zombies
            """
            return len(self._zombie_list)

        def zombies(self):
            """
            Generator that yields the zombies in the order they were
            added.
            """
            # replace with an actual generator
            for cell in self._zombie_list:
                yield cell

        def add_human(self, row, col):
            """
            Add human to the human list
            """
            self._human_list.append((row, col))

        def num_humans(self):
            """
            Return number of humans
            """
            return len(self._human_list)

        def humans(self):
            """
            Generator that yields the humans in the order they were added.
            """
            # replace with an actual generator
            for cell in self._human_list:
                yield cell

        def compute_distance_field(self, entity_type):
            """
            Function computes a 2D distance field
            Distance at member of entity_queue is zero
            Shortest paths avoid obstacles and use distance_type distances
            """
            self._height = self.get_grid_height()
            self._width  = self.get_grid_width()

            self._visited = poc_grid.Grid(self._height, self._width)
            self._distance_field = [[self._height * self._width for dummy_col in range(self._width)] 
                              for dummy_row in range(self._height)]

            self._boundry = poc_queue.Queue()
            if entity_type == HUMAN:
                for cell in self.humans():
                    self._boundry.enqueue((cell[0], cell[1]))
                    self._visited.set_full(cell[0], cell[1])
                    self._distance_field[cell[0]][cell[1]] = 0
            elif entity_type == ZOMBIE:
                for cell in self.zombies():
                    self._boundry.enqueue((cell[0], cell[1]))
                    self._visited.set_full(cell[0], cell[1])
                    self._distance_field[cell[0]][cell[1]] = 0      

            #while boundary is not empty:
            #    current_cell  ←  dequeue boundary
            #    for all neighbor_cell of current_cell:
            #        if neighbor_cell is not in visited:
            #        add neighbor_cell to visited
            #        enqueue neighbor_cell onto boundary
            while self._boundry.__len__():
                current_cell = self._boundry.dequeue()
                neighbors = self.four_neighbors(current_cell[0], current_cell[1])
                for neighbor in neighbors:
                    if self._visited.is_empty(neighbor[0], neighbor[1]) and self.is_empty(neighbor[0], neighbor[1]):
                        self._visited.set_full(neighbor[0], neighbor[1])
                        self._boundry.enqueue(neighbor)
                        self._distance_field[neighbor[0]][neighbor[1]] = self._distance_field[current_cell[0]][current_cell[1]] + 1
            return self._distance_field

        def move_humans(self, zombie_distance):
            """
            Function that moves humans away from zombies, diagonal moves
            are allowed
            """
            next_human_list = []
            for current_cell in self.humans():
                _current_distance = zombie_distance[current_cell[0]][current_cell[1]]
                _distance_list = [[current_cell], [], []]
                neighbors = self.eight_neighbors(current_cell[0], current_cell[1])
                for neighbor in neighbors:
                    dummy_idx = zombie_distance[neighbor[0]][neighbor[1]] - _current_distance
                    if 0 <= dummy_idx < 3:
                        _distance_list[dummy_idx].append(neighbor)

                if len(_distance_list[2]) > 0:
                    next_cell = random.choice(_distance_list[2])
                elif len(_distance_list[1]) > 0:
                    next_cell = random.choice(_distance_list[1])
                else:
                    next_cell = random.choice(_distance_list[0])
                next_human_list.append(next_cell)
            self._human_list = next_human_list


        def move_zombies(self, human_distance):
            """
            Function that moves zombies towards humans, no diagonal moves
            are allowed
            """
            next_zombie_list = []
            for current_cell in self.zombies():
                _current_distance = human_distance[current_cell[0]][current_cell[1]]
                _distance_list = [[current_cell], []]
                neighbors = self.four_neighbors(current_cell[0], current_cell[1])
                for neighbor in neighbors:
                    dummy_idx = _current_distance - human_distance[neighbor[0]][neighbor[1]]
                    if dummy_idx >= 0:
                        _distance_list[dummy_idx].append(neighbor)

                if len(_distance_list[1]) > 0:
                    next_cell = random.choice(_distance_list[1])
                else:
                    next_cell = random.choice(_distance_list[0])
                next_zombie_list.append(next_cell)
            self._zombie_list = next_zombie_list

    # Start up gui for simulation - You will need to write some code above
    # before this will work without errors

    poc_zombie_gui.run_gui(Zombie(30, 40))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值