1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

「世界で闘うプログラミング力を鍛える本」Pythonコード解答例 - 3.1 3つのスタック

Last updated at Posted at 2020-02-07

「世界で闘うプログラミング力を鍛える本」Pythonコード解答例 - 3.1 3つのスタック

###CHAP3. スタックとキュー

  1. 3つのスタック

#Pythonコード解答例


class FixedMultiStack:

    def __init__(self, stackSize):
        numberOfStacks = 3
        self.stackCapacity = stackSize
        self.values = [0] * (stackSize * numberOfStacks) 
        self.sizes = [0] * numberOfStacks

    def indexOfTop(self,stackNum):
        offset = stackNum * self.stackCapacity
        size = self.sizes[stackNum]
        return offset + size - 1

    def isFull(self,stackNum):
        return self.sizes[stackNum] == self.stackCapacity

    def push(self,stackNum,value):
        if self.isFull(stackNum):
            raise Exception("FullStackException")
        self.sizes[stackNum] = self.sizes[stackNum] + 1
        self.values[self.indexOfTop(stackNum)] = value

    def isEmpty(self,stackNum):
        return self.sizes[stackNum] == 0

    def pop(self,stackNum):
        if self.isEmpty(stackNum):
            raise Exception("EmptyStackException")
        topIndex = self.indexOfTop(stackNum)
        value = self.values[topIndex]
        self.values[topIndex] = 0
        self.sizes[stackNum] = self.sizes[stackNum] - 1
        return value

    def peek(self,stackNum):
        if self.isEmpty(stackNum):
            raise Exception("EmptyStackException")
        return self.values[self.indexOfTop(stackNum)]

FMS = FixedMultiStack(5)

print(FMS.values)

FMS.push(0,1)
FMS.push(1,6)
FMS.push(2,11)

print(FMS.values)

FMS.push(0,2)
FMS.push(0,3)
FMS.push(0,4)
FMS.push(0,5)

print(FMS.values)

FMS.pop(0)
FMS.pop(1)

print(FMS.values)

print(FMS.peek(0))
print(FMS.peek(2))
1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?