Python单链表的简单实现方法,python单链实现

来源:http://www.sh-fengwen.com 作者:美高梅游戏平台网站 人气:129 发布时间:2019-09-04
摘要:Python实现简单状态框架的方法,python实现框架 本文实例讲述了Python实现简单状态框架的方法。分享给大家供大家参考。具体分析如下: 这里使用Python实现一个简单的状态框架,代码需

Python实现简单状态框架的方法,python实现框架

本文实例讲述了Python实现简单状态框架的方法。分享给大家供大家参考。具体分析如下:

这里使用Python实现一个简单的状态框架,代码需要在python3.2环境下运行

复制代码 代码如下:from time import sleep
from random import randint, shuffle
class StateMachine(object):
    ''' Usage:  Create an instance of StateMachine, use set_starting_state(state) to give it an
        initial state to work with, then call tick() on each second (or whatever your desired
        time interval might be. '''
    def set_starting_state(self, state):
        ''' The entry state for the state machine. '''
        state.enter()
        self.state = state
    def tick(self):
        ''' Calls the current state's do_work() and checks for a transition '''
        next_state = self.state.check_transitions()
        if next_state is None:
            # Stick with this state
            self.state.do_work()
        else:
            # Next state found, transition to it
            self.state.exit()
            next_state.enter()
            self.state = next_state
class BaseState(object):
    ''' Usage: Subclass BaseState and override the enter(), do_work(), and exit() methods.
            enter()    -- Setup for your state should occur here.  This likely includes adding
                          transitions or initializing member variables.
            do_work()  -- Meat and potatoes of your state.  There may be some logic here that will
                          cause a transition to trigger.
            exit()     -- Any cleanup or final actions should occur here.  This is called just
                          before transition to the next state.
    '''
    def add_transition(self, condition, next_state):
        ''' Adds a new transition to the state.  The "condition" param must contain a callable
            object.  When the "condition" evaluates to True, the "next_state" param is set as
            the active state. '''
        # Enforce transition validity
        assert(callable(condition))
        assert(hasattr(next_state, "enter"))
        assert(callable(next_state.enter))
        assert(hasattr(next_state, "do_work"))
        assert(callable(next_state.do_work))
        assert(hasattr(next_state, "exit"))
        assert(callable(next_state.exit))
        # Add transition
        if not hasattr(self, "transitions"):
            self.transitions = []
        self.transitions.append((condition, next_state))
    def check_transitions(self):
        ''' Returns the first State thats condition evaluates true (condition order is randomized) '''
        if hasattr(self, "transitions"):
            shuffle(self.transitions)
            for transition in self.transitions:
                condition, state = transition
                if condition():
                    return state
    def enter(self):
        pass
    def do_work(self):
        pass
    def exit(self):
        pass
##################################################################################################
############################### EXAMPLE USAGE OF STATE MACHINE ###################################
##################################################################################################
class WalkingState(BaseState):
    def enter(self):
        print("WalkingState: enter()")
        def condition(): return randint(1, 5) == 5
        self.add_transition(condition, JoggingState())
        self.add_transition(condition, RunningState())
    def do_work(self):
        print("Walking...")
    def exit(self):
        print("WalkingState: exit()")
class JoggingState(BaseState):
    def enter(self):
        print("JoggingState: enter()")
        self.stamina = randint(5, 15)
        def condition(): return self.stamina <= 0
        self.add_transition(condition, WalkingState())
    def do_work(self):
        self.stamina -= 1
        print("Jogging ({0})...".format(self.stamina))
    def exit(self):
        print("JoggingState: exit()")
class RunningState(BaseState):
    def enter(self):
        print("RunningState: enter()")
        self.stamina = randint(5, 15)
        def walk_condition(): return self.stamina <= 0
        self.add_transition(walk_condition, WalkingState())
        def trip_condition(): return randint(1, 10) == 10
        self.add_transition(trip_condition, TrippingState())
    def do_work(self):
        self.stamina -= 2
        print("Running ({0})...".format(self.stamina))
    def exit(self):
        print("RunningState: exit()")
class TrippingState(BaseState):
    def enter(self):
        print("TrippingState: enter()")
        self.tripped = False
        def condition(): return self.tripped
        self.add_transition(condition, WalkingState())
    def do_work(self):
        print("Tripped!")
        self.tripped = True
    def exit(self):
        print("TrippingState: exit()")
if __name__ == "__main__":
    state = WalkingState()
    state_machine = StateMachine()
    state_machine.set_starting_state(state)
    while True:
        state_machine.tick()
        sleep(1)

希望本文所述对大家的Python程序设计有所帮助。

本文实例讲述了Python实现简单状态框架的方法。分享给大家供大家参考。具体分析如下: 这...

Python单链表的简单实现方法,python单链实现

本文实例讲述了Python单链表的简单实现方法,分享给大家供大家参考。具体方法如下:

通常来说,要定义一个单链表,首先定义链表元素:Element.它包含3个字段:

list:标识自己属于哪一个list
datum:改元素的value
next:下一个节点的位置

具体实现代码如下:

class LinkedList(object):

  class Element(object):

    def __init__(self,list,datum,next): 
      self._list = list
      self._datum = datum 
      self._next = next

    def getDatum(self): 
      return self._datum

    datum = property(
      fget = lambda self: self.getDatum())

    def getNext(self):
      return self._next

    next = property(
      fget = lambda self: self.getNext())

  def __init__(self):

    self._head = None
    self._tail = None
  def getHead(self):
    return self._head 
  head = property(
    fget = lambda self: self.getHead()) 
  def prepend(self,item):
    tmp = self.Element (self,item,self._head)
    if self._head is None:
      self._tail = tmp 
    self._head = tmp 

  def insert(self, pos, item):
    i = 0
    p = self._head
    while p != None and i < pos -1:
      p = p._next
      i += 1
    if p == None or i > pos-1:
      return -1
    tmp = self.Element(self, item, p._next)
    p._next = tmp
    return 1
  def getItem(self, pos):
    i = 0
    p = self._head
    while p != None and i < pos -1:
      p = p._next
      i += 1
    if p == None or i > post-1:
      return -1
    return p._datum
  def delete(self, pos):
    i = 0
    p = self._head
    while p != None and i < pos -1:
      p = p._next
      i += 1
    if p == None or i > post-1:
      return -1
    q = p._next
    p._nex = q._next
    datum = p._datum
    return datum
  def setItem(self, pos, item):
    i = 0
    p = self._head
    while p != None and i < pos -1:
      p = p._next
      i += 1
    if p == None or i > post-1:
      return -1
    p._datum = item
    return 1
  def find(self, pos, item):
    i = 0
    p = self._head
    while p != None and i < pos -1:
      if p._datum == item:
        return 1
      p = p._next
      i += 1
    return -1
  def empty(self):
    if self._head == None:
      return 1
    return 0
  def size(self):
    i = 0
    p = self._head
    while p != None and i < pos -1:
      p = p._next
      i += 1
    return i

  def clear(self):
    self._head = None
    self._tail = None

test = LinkedList()
test.prepend('test0')
print test.insert(1, 'test')
print test.head.datum
print test.head.next.datum

希望本文所述对大家的Python程序设计有所帮助。

python 怎用单向循环链表实现堆栈

Node没什么问题,就是变量定义的时候是一个下划线而不是两个
Stack这里有点问题,
(不知道你这里为啥需要做成一个循环的链表,不过不管了)
首先你得定义一个head和一个tail,这样的话才能把tail和head连接形成一个循环
初始化Stack的话把head和tail都设置成None表示这是个空的stack
push的话看你喜欢这么写了,比较喜欢的是把push进去的Node作为新的head,然后修改一下self._head为新Node,然后修改新Node的next为老的head,再连接一下Tail和Head便可,这样就省掉一些循环
pop的话就加一些判定好了,首先看Head是不是None,如果是就说明Stack是空的。如果发现Tail和Head都是同一个的话就说明Stack里就一项了,提取完Head之后就设置Stack为空吧。然后先提取Head,然后读取Head后面的那一个Node并且设置为新的Head,然后再连接一下Tail和Head便可
附上代码供参考.
class Node: def __init__(self, newData): self._data = newData self._next = None def getData(self): return self._data def getNext(self): return self._next def setData(self, newData): self._data = newData def setNext(self, newNode): self._next = newNodeclass Stack: def __init__(self): self._head = None self._tail = None def push(self, data): print 'Push',data,'into stack' new = Node(data) cur = self._head end = self._tail if cur is None: self._head = new new.setNext(new) self._tail = new else: new.setNext(self._head) self._head = new self._tail.setNext(new) def pop(self): if self._head is not None: cur = self._head print 'pop',cur.getData(),'out of stack' if cur.getNext() is not cur: self._head = cur.getNext() self._tail.setNext(self._head) else: ......余下全文>>  

本文由美高梅游戏平台网站发布于美高梅游戏平台网站,转载请注明出处:Python单链表的简单实现方法,python单链实现

关键词:

上一篇:python基本语法练习,python基本语法

下一篇:没有了

最火资讯