Esempio n. 1
0
 def test_empty_pop(self):
     testStack = Stack()
     testStack.append('a')
     testStack.pop()
     self.assertEqual(testStack.size(), 0)
     with self.assertRaises(Exception):
         testStack.pop()
Esempio n. 2
0
def calculate(input_expression):
    input_expression = input_expression.split()
    stack = Stack()
    for n in input_expression:
        try:
            stack.append(int(n))
        except ValueError:
            try:
                op = ops[n]
                op(stack)
            except KeyError:
                raise ValueError("unknown operator {}".format(n))
    return stack
Esempio n. 3
0
 def test_last_on_top(self):
     testStack = Stack()
     testStack.append('a')
     testStack.append(4)
     testStack.append(54)
     testStack.append('b')
     self.assertEqual(testStack.peek(), 'b')
Esempio n. 4
0
class Player:

    # constructor used to create a new player at the beginning of a Game
    def __init__(self, game, strategy=None, **kwargs):

        # kingdom is passed to each Player
        # and gets modified during buy()
        self.game = game
        if strategy is None:
            self.strategy = BigMoney(self, self.game.kingdom.stacks)
        else:
            self.strategy = strategy(self, self.game.kingdom.stacks, **kwargs)

        # name is name of strategy with unique tag to account for multiple copies of the same strat
        self.name = str(self.strategy) + '_' + str(id(self))

        self.discard_pile = Stack(cards=list(
            map(lambda x: Card(x, self.game), 7 * ['Copper'] +
                3 * ['Estate'])))
        self.draw_pile = Stack(cards=[])
        self.hand = Hand(cards=[])
        self.deck = Deck(cards=self.discard_pile.cards + self.draw_pile.cards)
        self.reshuffle()
        self.draw(5)

        return None

    # private method to reshuffle
    def reshuffle(self):

        if self.game.verbose:
            print("   reshuffles")
        self.draw_pile = Stack(cards=self.discard_pile.cards)
        self.discard_pile = Stack(cards=[])
        self.draw_pile.shuffle()

        return None

    # private method to draw n cards
    def draw(self, n):

        for i in range(n):
            if self.draw_pile.size() == 0:
                if self.discard_pile.size() > 0:
                    self.reshuffle()
                else:
                    if self.game.verbose:
                        print("   has exhausted deck")
                    return None
            popped = self.draw_pile.pop()
            if self.game.verbose:
                print("   draws " + str(popped))
            self.hand.extend([popped])

#        print(self.hand.names())
        return None

####Discard functions

    def discard(self, n):

        if n == self.hand.size():
            self.discards = tuple(self.hand.cards)
#            print(discards)
#            print(self.hand.cards)
        else:
            self.discards = tuple(self.strategy.discard(self, n))

        for c in self.discards:
            if self.game.verbose:
                print("   discards " + str(c))
            self.hand.remove(c)
#            print('  discard' + str(c))
        self.discard_pile.extend(self.discards)
        del self.discards
        return None

    def discard_to(self, n):
        self.discard(self.hand.size() - n)
        return None

####Functions  for other to do

    def others_draw(self, n):
        for p in self.game.other_players:
            p.draw(n)
        return None

    def others_discard_to(self, n):
        for p in self.game.other_players:
            p.discard_to(n)
        return None

    def others_discard(self, n):
        for p in self.game.other_players:
            p.discard(n)
        return None

    def others_gain(self, card):
        for p in self.game.other_players:
            p.gain(card)
        return None

####Trash function

    def trash(self):
        self.trashers = tuple(self.strategy.trash(self))
        for c in self.trashers:
            if self.game.verbose:
                print("   trashes " + str(c))
            self.hand.remove(c)
            self.deck.remove(c)
        self.game.kingdom.stacks['Trash'].extend(self.trashers)
        #        print('   Trashing the following cards' + str(self.trashers))

        del self.trashers
        return None

####Cycle function for cellar (maybe others???)

    def cycle(self):
        self.numCycle = self.strategy.cycle(self)
        self.discard(self.numCycle)
        self.draw(self.numCycle)

        return None

    # take turn by passing self to self's strategy, which calls play_action(), buy() and cleanup()
    def take_turn(self):

        self.actions = 1
        self.buys = 1
        self.coins = 0
        self.in_play = Stack(cards=[])
        self.strategy.take_turn(self)  # magic happens here
        self.cleanup()

    def cleanup(self):

        if self.in_play.size() > 0:
            self.discard_pile.extend(self.in_play.pop_all())
        self.discard(self.hand.size())
        self.draw(5)

    def buy(self, card):
        if self.game.verbose:
            print("   has hand: ", self.hand.names())
            print("   buys " + card)

        popped = self.gain(card)
        self.coins -= popped.cost
        self.buys -= 1
        return None

    def gain(self, card):
        if self.game.kingdom.stacks[card].size() > 0:
            popped = self.game.kingdom.pop(card)
            self.discard_pile.extend([popped])
            self.deck.extend([popped])
        else:
            if self.game.verbose:
                print("   " + card + " stack is empty!")
            popped = None
        return popped

    def play_action(self, card_name):
        assert card_name in self.hand.names(
        ), "Playing a card you don't have? Cheater!"
        card = self.hand.first(card_name)
        if self.game.verbose:
            print("   has hand: ", self.hand.names())
            print("   plays " + card_name)
        self.hand.remove(card)
        self.in_play.append(card)
        self.actions -= 1
        card.card_action()
        return None
Esempio n. 5
0
class Interpreter(object):
    def __init__(self, source, output, *args):
        self.stack = Stack(args)
        self.source = source
        self.scope = []
        self.pointer = 0
        self.output = output

    def step(self):
        if self.pointer >= len(self.source): return False
        command = self.source[self.pointer]
        if command == "[":
            if self.stack[-1]:
                self.scope.append(self.pointer)
            else:
                #If the TOS is zero jump to the next ]
                tempScope = 1
                while tempScope and (self.pointer < len(self.source)):
                    self.pointer += 1
                    if self.source[self.pointer] == "]":
                        tempScope -= 1
                    elif self.source[self.pointer] == "[":
                        tempScope += 1
        elif command == "]":
            if self.stack[-1]:
                self.pointer = self.scope[-1]
            else:
                self.scope.pop()
        elif command == "&":
            self.stack.append(self.stack.pop() & self.stack.pop())
        elif command == "|":
            self.stack.append(self.stack.pop() | self.stack.pop())
        elif command == "^":
            self.stack.append(self.stack.pop() ^ self.stack.pop())
        elif command == "~":
            self.stack.append(~self.stack.pop())
        elif command == "-":
            self.stack.append(-self.stack.pop())
        elif command == "<":
            self.stack.append(self.stack.pop() << 1)
        elif command == ">":
            self.stack.append(self.stack.pop() >> 1)
        elif command == ":":
            if self.stack:
                self.stack.append(self.stack[-1])
            else:
                self.stack = [0]
        elif command == "?":
            if self.stack:
                self.stack = Stack([self.stack.pop()] + self.stack)
        elif command == "!":
            if self.stack:
                self.stack = Stack(self.stack[1:] + [self.stack[0]])
        self.pointer += 1
        return True

    def __str__(self):
        functions = {
            "i": str,
            "b": lambda x: "-" + bin(x)[3:] if x < 0 else bin(x)[2:],
            "a": lambda x: chr(x % 256)
        }
        return ("" if self.output == "a" else " ").join(
            map(functions[self.output], self.stack))
Esempio n. 6
0
class Interpreter(object):
	def __init__(self,source,input,startx=None,starty=None,dir=None):
		source = source.strip().split("\n")
		dim = max(map(len,source)+[len(source)])
		self.source = [list(x.ljust(dim,"."))for x in source]
		self.dim = (len(self.source),len(self.source[0]))
		if dir == None:
			self.direction = [[1,0],[0,1],[-1,0],[0,-1]][randint(0,3)]
		else:
			self.direction = dir
		if (startx,starty) == (None,None):
			self.location = [randint(0,self.dim[0]-1),randint(0,self.dim[1]-1)]
		else:
			self.location = [startx,starty]
		self.memory = Stack(input)
		self.scope = Stack()
		self.read = False
		self.safety = False
	def wrapAround(self):
 		self.location[0] %= self.dim[0]
		self.location[1] %= self.dim[1]
	def move(self):
		self.location = [
			self.location[0]+self.direction[0],
			self.location[1]+self.direction[1]
		]
		#Important bit
		if self.location[0] < 0:
			self.wrapAround()
		if self.location[1] < 0:
			self.wrapAround()
		if self.location[0] >= self.dim[0]:
			self.wrapAround()
		if self.location[1] >= self.dim[1]:
			self.wrapAround()
	def character(self):
		return self.source[self.location[0]][self.location[1]]
	def action(self):
		if self.read:
			if self.character() == '"':
				self.read = False
			else:
				self.memory.append(ord(self.character()))
		elif self.character() == "/":
			self.direction = map(lambda x:-x,self.direction[::-1])
		elif self.character() == "\\":
			self.direction = self.direction[::-1]
		elif self.character() == "|":
			self.direction[1] *= -1
		elif self.character() == ">":
			self.direction = [0,1]
		elif self.character() == "<":
			self.direction = [0,-1]
		elif self.character() == "v":
			self.direction = [1,0]
		elif self.character() == "^":
			self.direction = [-1,0]
		elif self.character() == "%":
			self.safety = True
		elif self.character() == "#":
			self.safety = False
		elif self.character() == "@":
			if self.safety:
				self.direction = [0,0]
		elif self.character() == "[":
			if self.direction[1] == 1:
				self.direction[1] = -1
			if self.direction[1]:
				self.source[self.location[0]][self.location[1]] = "]"
		elif self.character() == "]":
			if self.direction[1] == -1:
				self.direction[1] = 1
			if self.direction[1]:
				self.source[self.location[0]][self.location[1]] = "["
		elif self.character() in "0123456879":
			self.memory.append(int(self.character()))
		elif self.character() == "+":
			self.memory.append(self.memory.pop()+self.memory.pop())
		elif self.character() == "*":
			self.memory.append(self.memory.pop()*self.memory.pop())
		elif self.character() == "-":
			self.memory.append(-self.memory.pop())
		elif self.character() == ":":
			self.memory.append(self.memory[-1])
		elif self.character() == "$":
			a,b=self.memory.pop(),self.memory.pop()
			self.memory.append(a)
			self.memory.append(b)
		elif self.character() == "!":
			self.move()
		elif self.character() == "?":
			if self.memory.pop():
				self.move()
		elif self.character() == "(":
			self.scope.append(self.memory.pop())
		elif self.character() == ")":
			self.memory.append(self.scope.pop())
		elif self.character() == '"':
			self.read = True
	def output(self,screen,a,b):
		try:
			import curses
			curselib = curses
		except ImportError:
			import unicurses
			curselib = unicurses

		for x in range(self.dim[0]):
			for y in range(self.dim[1]):
				try:
					if [x,y] == self.location:
						if curselib.has_colors():
							screen.addstr(a+x,b+y*2,"X",curselib.color_pair(1))
						else:
							screen.addstr(a+x,b+y*2,"X")
					else:
						screen.addstr(a+x,b+y*2,self.source[x][y])
				except:pass
Esempio n. 7
0
class Parser(object):
    def __init__(self):
        self._stack = Stack(
        )  # Stack where the information on open HTML tags is stored
        self._html = ['<!DOCTYPE html>', '<html>',
                      '<body>']  # output list, stores HTML code
        self._stack.append(MarkdownSection.Html)
        self._stack.append(MarkdownSection.Body)
        # list of all functions which handle the appriopriate text type
        self._nonBlockHandlers = [
            self.handleHeading, self.handleBoldItalid, self.handleBold,
            self.handleItalic, self.handleurl, self.handleUnknown
        ]
        self._handlers = [
            self.handleEmpty, self.handleCode, self.handleBlockquotes,
            self.handleList
        ] + self._nonBlockHandlers

        self.MetaData = {}  # stores metadata of the md file,
        #i.e. title, date: 2019-04-12, tags, theme (style or dark)

    def parse(self, text: str):
        """main function - splits given text by enters"""
        lines = text.split('\n')
        if len(lines) < 6:
            raise Exception('No meta data or too short')
        metadata = lines[:
                         6]  # retrieves metadata (by calling appriopriate function)
        rest = lines[7:]
        self.handleMetaData(metadata)
        list(map(lambda x: self.parseNewLine(x),
                 rest))  # parses every line of text
        while self._stack.size(
        ):  # closes all open tags at the end of the file
            self.closeHtmlTag(self._stack.pop())

        return '\n'.join(self._html)  # returns a string with HTML code

    def closeHtmlTag(self, tagType: MarkdownSection):
        """closes last tag from the stack
        tag types are defined within Markdown class"""
        if tagType in ListUnorderedElements:
            self._html.append("</ul>")
            return
        if tagType == MarkdownSection.ListOrdered:
            self._html.append("</ol>")
        if tagType == MarkdownSection.Html:
            self._html.append("</html>")
        if tagType == MarkdownSection.Body:
            self._html.append("</body>")
        if tagType == MarkdownSection.Paragraph:
            self._html.append("</p>")
        if tagType == MarkdownSection.BlockOfCode:
            self._html.append("</div>")
        if tagType == MarkdownSection.Blockquotes:
            self._html.append("</blockquote>")

    def handleNewList(self, currentListType: MarkdownSection, spacesCount: int,
                      text: str):
        """function to handle nested lists
        it checks the level of nesting
        and parses the text additionally (checks for bold or italic text etc)"""

        nestLevel = self._stack.check_level(currentListType)
        if not spacesCount:
            spacesCount = ''
        currentLevel = int(len(spacesCount) / 4) + 1

        if currentLevel < nestLevel:
            while currentLevel < nestLevel:
                currentElement = self._stack.pop()
                if currentElement == currentListType:
                    nestLevel -= 1
                self.closeHtmlTag(currentElement)
        elif currentLevel - 1 == nestLevel:
            self._stack.append(currentListType)
            if currentListType == MarkdownSection.ListOrdered:
                self._html.append("<ol>")
            else:
                self._html.append("<ul>")

        return f"<li>{self.parseText(text)}</li>"

    def closeList(self):
        """closes list HTML tags checking first the list type"""
        for listType in ListUnorderedElements:
            level = self._stack.check_level(listType)
            while level:
                currentElement = self._stack.pop()
                if currentElement == listType:
                    level -= 1
                self.closeHtmlTag(currentElement)

    def handleList(self, line: str):
        """function for parsing lists (both ordered and unordered)"""
        regex = re.search(r"^( *)([+\-*]|\d\.) (.*)$",
                          line)  # regex to match +, -, * or digit.
        if regex and regex.group(2):
            if regex.group(2) == "+" or regex.group(2) == "-" or regex.group(
                    2) == "*":
                return self.handleNewList(MarkdownSection.ListUnorderedPlus,
                                          regex.group(1), regex.group(3))
            else:
                return self.handleNewList(MarkdownSection.ListOrdered,
                                          regex.group(1), regex.group(3))
            return None
        self.closeList()

    def handleHeading(self, line: str):
        """function for parsing heads"""
        regex = re.search(r"^(#+) (.*)$",
                          line)  # regex to match #### head (any number of #'s)
        if regex:
            headingType = len(regex.group(1))
            headingValue = regex.group(2)
            return f"<h{headingType}>{headingValue}</h{headingType}>"

    def handleBold(self, line: str):
        """function for parsing bold text"""
        regex = re.search(r"^(.*)(\*\*|\_\_)([^*_]+)(\*\*|\_\_)(.*)$", line)
        if regex:  # regex to match ** ** or __ __
            textBefore = regex.group(1)
            textBold = regex.group(3)
            textAfter = regex.group(5)
            return f"{self.parseText(textBefore)}<strong>{self.parseText(textBold)}</strong>{self.parseText(textAfter)}"

    def handleUnknown(self, line: str) -> str:
        """function for parsing normal text 
        or text with symbols not defined as special characters"""
        return line

    def handleItalic(self, line: str):
        """function for parsing italic text"""
        regex = re.search(r"^(.*)([\*\_])([^*_]+)([\*\_])(.*)$", line)
        if regex:  # regex to match * * or _ _
            textBefore = regex.group(1)
            textItalic = regex.group(3)
            textAfter = regex.group(5)
            return f"{self.parseText(textBefore)}<em>{self.parseText(textItalic)}</em>{self.parseText(textAfter)}"

    def handleBoldItalid(self, line: str):
        """function for parsing bold and italic text"""
        regex = re.search(r"^(.*)(\*\*\*|\_\_\_)([^*_]+)(\*\*\*|\_\_\_)(.*)$",
                          line)
        if regex:  # regex to match *** *** or ___ ___
            textBefore = regex.group(1)
            textBoldandItalic = regex.group(3)
            textAfter = regex.group(5)
            return f"{textBefore}<strong><em>{textBoldandItalic}</em></strong>{textAfter}"

    def handleurl(self, line: str):
        """function for parsing links"""
        regex = re.search(r"^(.*)\[(.*)\]\((https:.*)\)(.*)$", line)
        if regex:
            txtBefore = regex.group(1)
            urlText = regex.group(2)
            urlHtml = regex.group(3)
            txtAfter = regex.group(4)
            return f"{txtBefore}<a href='{urlHtml}'>{urlText}</a>{txtAfter}"

    def handleCode(self, line: str):
        """function for parsing block of code starting with ```"""
        regex = re.search(r"^(```).*$", line)
        if regex and self._stack.peek() != MarkdownSection.BlockOfCode:
            self._stack.append(MarkdownSection.BlockOfCode)
            return f"<div class='CodeBlock'>"
        elif regex and self._stack.peek() == MarkdownSection.BlockOfCode:
            self._stack.pop()
            return f"</div>"
        elif self._stack.peek() == MarkdownSection.BlockOfCode:
            line = html.escape(line)
            return f"{line}<br>"

    def handleBlockquotes(self, line: str):
        """function for parsing blockquote starting with >"""
        regex = re.search(r"^(>)(.*)$", line)
        if regex and self._stack.peek() != MarkdownSection.Blockquotes:
            self._stack.append(MarkdownSection.Blockquotes)
            txt = regex.group(2)
            return f"<blockquote class='QuotesBlock'>{txt}"

    def handleMetaData(self, lines: list):
        """retrieving metadata and saving to dictionary
        metadata attributes are then used to define a style of the file"""
        if len(lines) < 6:
            raise Exception('No meta data or wrong format')

        data = lines[1:-1]
        for line in data:
            lineSplit = line.split(": ")
            key = lineSplit[0]
            value = lineSplit[1].strip()
            self.MetaData[key] = value
        self._html.append("<head>")
        self._html.append(
            f'<meta name="keywords" content="{self.MetaData["tags"]}">')
        self._html.append(f"<title>{self.MetaData['title']}</title>")
        self._html.append(
            f'<link rel="stylesheet" href="{self.MetaData["theme"]}.css">')
        self._html.append("</head>")

    def handleEmpty(self, line: str):
        """empty lines indicates opening or starting a new paragraph
        empty line == line with spaces, tabs etc"""
        regex = re.search(r"^\s*$", line)
        if line == '' or regex:
            self.closeList()
            if self._stack.peek() == MarkdownSection.EmtpyLine:
                return
            if self._stack.peek() == MarkdownSection.BlockOfCode:
                self._html.append(f"{line}<br>")
                return
            if self._stack.peek() == MarkdownSection.Blockquotes:
                self.closeHtmlTag(self._stack.pop())
            if self._stack.peek() == MarkdownSection.Paragraph:
                self.closeHtmlTag(MarkdownSection.Paragraph)
                self._stack.pop()
            self._stack.append(MarkdownSection.EmtpyLine)
        elif self._stack.peek() == MarkdownSection.EmtpyLine:
            self._stack.pop()
            self._stack.append(MarkdownSection.Paragraph)
            self._html.append("<p>")

    def parseNewLine(self, line: str):
        """parse every line by checking every regex"""
        for handler in self._handlers:
            res = handler(line)
            if res:
                self._html.append(res)
                return

    def parseText(self, line: str):
        """non block handlers for nested special characters"""
        for handler in self._nonBlockHandlers:
            res = handler(line)
            if res:
                return res
        return ''
Esempio n. 8
0
                raise ValueError
            ok = True
        except ValueError:
            print("Invalid value!")

    s = Stack(capacity)
    while True:
        cls()
        print_status(s)
        choice = dictionary.get(input("> ").lower(), -1)
        if choice == 1:
            value = input("value> ")
            while not len(value) > 0:
                print("Value cannot be empty.")
                value = input("value> ")
            if not s.append(value):
                print("Stack is full")
        elif choice == 2:
            value = s.pop()
            if not value:
                print("Stack is empty")
        elif choice == 3:
            s.sort()
        elif choice == 0:
            break
        else:
            print("Invalid command")
            print_help(s)
        s.print()
        if s.is_empty():
            print("The stack is empty")
Esempio n. 9
0
 def test_level(self):
     testStack = Stack()
     testStack.append('a')
     testStack.append(4)
     testStack.append('a')
     testStack.append('b')
     testStack.append(6)
     testStack.append(75)
     testStack.append('a')
     self.assertEqual(testStack.check_level('a'), 3)
Esempio n. 10
0
 def test_append(self):
     testStack = Stack()
     testStack.append('a')
     testStack.append(6754)
     testStack.append([7, 5, 6, 'a'])
     self.assertEqual(testStack.size(), 3)