没事写个循环数组

2017-05-04  本文已影响0人  ic_bbc

新岗位需要用python,之前没写过python,用循环数组实现一个定长队列玩一下:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

class CirArray:
    
    readind = 0
    writeind = 0
    fullFlag = False
    emptyFlag = True
    
    def __init__(self, queneSize):
        if isinstance(queneSize, int) and queneSize >0:
            self.MAX_SIZE = queneSize
            self.DataSet = [0 for n in range(self.MAX_SIZE)]
        else:
            raise Exception('queneSize is invalid');

    def CirPop(self):
        if self.emptyFlag:
            print 'quene is empty and get failed'
            print "the quene is:",self.DataSet
            return False

        self.readind = (self.readind + 1)%self.MAX_SIZE
        print "pop value: ",self.DataSet[self.readind]
        self.DataSet[self.readind] = 0

        if self.writeind == self.readind:
            self.emptyFlag = True
            print 'quene is empty'
        print "the quene is:",self.DataSet


    def CirPush(self, num):
        if self.fullFlag:
            print 'quene is full and insert failed'
            print "the quene is:",self.DataSet
            return False

        self.writeind = (self.writeind + 1)%self.MAX_SIZE
        self.DataSet[self.writeind] = num
        print "push success:",num
        if self.emptyFlag:
            self.emptyFlag = False

        if self.writeind == self.readind:
            self.fullFlag = True
            print 'quene is full'
        print "the quene is:",self.DataSet

testArr = CirArray(10)
testArr.CirPush(1)
testArr.CirPush(3)
testArr.CirPop()

想说一下:
1、python类中使用成员变量写self好麻烦,简直赶上php的$了
2、后面可以改进成用动态数组实现不定长队列
3、只有pop和push函数没法发挥底层数组实现的优势,可以添加随机访问的接口

就到这里了,今后要经常写python了,先混个脸熟呗

上一篇下一篇

猜你喜欢

热点阅读