Ejemplo n.º 1
0
def stackReverser(in_stack):
    if not isinstance(in_stack, Stack):
        return 'err'
    reverse_stack = Stack()
    while in_stack.length() > 0:
        reverse_stack.push(in_stack.pop())
    return reverse_stack
Ejemplo n.º 2
0
def queue_reverser(queue):
    new_queue = Queue()
    stack = Stack()
    length = queue.length
    for _ in range(length):
        item = queue.dequeue()
        stack.push(item)
        queue.enqueue(item)
    for _ in range(length):
        new_queue.enqueue(stack.pop())
    return new_queue
Ejemplo n.º 3
0
def color_tetris(stacks, colours, rounds, th, secs):
    """ Play multi-stack colour tetris.

    Args:
        stacks - (int) number of stacks
        colours - (int) number of colours
        rounds - (int) number of blocks to be generated
        th  - (int) threshold height for a stack (if any stack exceeds this
              height, the game is over)
        secs - (int) number of seconds available for each move.
    """
    stacklist = []
    for i in range(stacks):
        stacklist.append(Stack())
    charstr = 'RGBOYIV'

    #generate the list of blocks
    blocklist = []
    for i in range(rounds):
        blocklist.append(charstr[random.randint(0,colours-1)])
    i = 0
    matches = 0
    threshold = True

    #reveal each block in turn, until exhausted or threshold breached
    while i < len(blocklist) and threshold:
        block = blocklist[i]
        i = i+1
        #display the block and get the user response
        output = str(i) + ': ' + block + '?'
        clocktime0 = time.time()
        ans = input(output)
        clocktime1 = time.time()
        elapsed = clocktime1 - clocktime0
        #now propcess the user response
        if elapsed > secs:
            print('TOO LATE (', elapsed, ' sec), block add to stack 1')
            ans = '1'
        if ans in['1','2','3','4']:
            value = int(ans)-1
        else:
            value = 0
        #now try to match the block with the top of the user's chosen stack
        if stacklist[value].top() == block:   #successful match
            stacklist[value].pop()
            print(' ******************************** ')
            matches = matches + 1
        else:                                 #failed match, so grow the stack
            stacklist[value].push(block)
        if stacklist[value].length() >= th:
            threshold = False
        else:
            j = 0
            while j < len(stacklist):
                print((j+1), ':', stacklist[j])
                j = j+1
    if threshold:
        print('Congratulations! You beat the system, and made', matches, 'matches.')
    else:
        print('You lasted for', i, 'rounds, and made', matches, 'matches.')
Ejemplo n.º 4
0
def game(no_of_stacks=3, no_of_games=1, max_length=6, turn_time=5):
    """Game of tetris

    Args:
        no_of_stacks: int -- How many rows to play (Default value: 3)
        no_of_games: int -- Number of rounds to play (Default value: 1)
        max_length: int -- Maximum height of blocks on the stack (Default value: 6)
        turn_time: int -- Time in seconds given to make each move (Default value: 5)
    """
    score = 0
    for game in range(no_of_games):
        # Number of blocks
        blocks = []
        for i in range(max_length):
            blocks.append(randint(0, 2))
        # Create stacks
        stack_list = []
        for i in range(no_of_stacks):
            stack_list.append(Stack())
        while len(blocks) > 0:
            # Check max length of stacks
            for check_stack in stack_list:
                if check_stack.length() > max_length:
                    break
            next = blocks.pop()
            print('------------\nTetris (press \'q\' to quit)\n------------')
            # Print stacks
            print()
            for index in range(no_of_stacks):
                print(index + 1, stack_list[index])
            print()
            print('Next -> ', next)
            print('Press \'p\' to pass or')

            # Get user input and time taken
            start = time()
            next_row = input('Select row: ')
            end = time()
            time_taken = end - start

            if next_row == 'q':
                break
            elif time_taken > turn_time:
                print('You took too long!')
                next_row = randint(0, no_of_stacks - 1)
            elif next_row in str(range(1, no_of_stacks + 1)):
                next_row = int(next_row) - 1
            else:
                next_row = randint(0, no_of_stacks - 1)

            if next == stack_list[next_row].top():
                score += 1
                stack_list[next_row].pop()
            else:
                stack_list[next_row].push(next)
    print('---------\nGame Over\nScore:', score, '\n---------')
Ejemplo n.º 5
0
def reverse_queue(queue):
    """ Reverse a queue.

    Note that this will destroy the original queue.

    Args:
        queue - a queue

    Returns the reverse of the input queue.
    """
    outqueue = QueueV3()
    stack = Stack()
    while not queue.length() == 0:
        item = queue.dequeue()
        stack.push(item)
        print('dequeued', item)
    while not stack.length() == 0:
        item = stack.pop()
        outqueue.enqueue(item)
        print('enqueued', item)
    return outqueue
Ejemplo n.º 6
0
def main():
    print('stackReverser\n')
    stack1 = Stack()
    alpha = ['a', 'b', 'c', 'd', 'e']
    alpha = [1, 2, 3]
    for i in range(len(alpha)):
        stack1.push(alpha[i])

    rev_stack = stackReverser(stack1)
    print(rev_stack)

    for i in range(stack1.length()):
        print(stack1.pop())

    for i in range(rev_stack.length()):
        print(rev_stack.pop())

    print(rev_stack)

    print('bracketChecker\n')
    test_string = '[he{}ll(ooo)oooooo(o)]'
    print(bracketChecker(test_string))
Ejemplo n.º 7
0
def reverse_queue2(queue):
    """ Reverse a queue.

    This will finish with the original queue in its original state.

    Args:
        queue - a queue

    Returns the reverse of the input queue.
    """
    outqueue = QueueV3()
    stack = Stack()
    i = queue.length()
    for pos in range(i):
        item = queue.dequeue()
        stack.push(item)
        print('dequeued', item)
        queue.enqueue(item)
    while not stack.length() == 0:
        item = stack.pop()
        outqueue.enqueue(item)
        print('enqueued', item)
    return outqueue
Ejemplo n.º 8
0
def palindrome_check_list(inlist):
    """ Determine whether inlist is a palindrome, using a stack.    """
    size = len(inlist)
    mid = size // 2
    even = True
    if size % 2 == 1:
        even = False
    print('Midpoint is', mid, '; inlist is of EVEN length:', even)
    stack = Stack()
    pos = 0
    while pos < mid:
        stack.push(inlist[pos])
        pos = pos + 1
    if not even:
        pos = pos + 1
    while pos < len(inlist):
        print('mylist[', pos, ']=', inlist[pos], '; stack.top() =',
              stack.top())
        #if inlist[pos] != stack.pop():
        if not inlist[pos].is_equal(stack.pop()):
            return False
        pos = pos + 1
    return True
Ejemplo n.º 9
0
def palindrome_check(string):
    """ Determine whether string is a palindrome, using a stack.    """
    mylist = list(string)
    size = len(mylist)
    mid = size // 2
    even = True
    if size % 2 == 1:
        even = False
    print('Midpoint is', mid, '; string is of EVEN length:', even)
    stack = Stack()  #create and return a stack object
    pos = 0
    while pos < mid:  #push first half of the string onto the stack
        stack.push(mylist[pos])
        pos = pos + 1
    if not even:
        pos = pos + 1
    while pos < len(mylist):  #now pop and compare the two half lists
        print('mylist[', pos, ']=', mylist[pos], '; stack.top() =',
              stack.top())
        if mylist[pos] != stack.pop():
            return False
        pos = pos + 1
    print('This is a palindrome')
    return True
Ejemplo n.º 10
0
def bracketChecker(input_string):
    open_brackets = ['(', '[', '{']
    close_brackets = [')', ']', '}']
    stack = Stack()
    for char in input_string:
        if char in open_brackets:
            stack.push(char)
        elif char in close_brackets:
            if char == ')':
                if stack.top() != '(':
                    return False
                stack.pop()
            elif char == ']':
                if stack.top() != '[':
                    return False
                stack.pop()
            elif char == '}':
                if stack.top() != '{':
                    return False
                stack.pop()
    return True
Ejemplo n.º 11
0
def postfix(string):
    """ Evaluate the postfix string, using a stack.

        Elements must be separated by spaces.
    """
    tokenlist = string.split()
    stack = Stack()
    for token in tokenlist:
        if token in ["+", "-", "*", "/"]:
            second = stack.pop()
            first = stack.pop()
            if token == "+":
                stack.push(first + second)
            elif token == "-":
                stack.push(first - second)
            elif token == "*":
                stack.push(first * second)
            else:
                stack.push(first / second)
        else:
            stack.push(int(token))
    return stack.pop()
Ejemplo n.º 12
0
def postfix_verbose(string):
    """ Evaluate the postfix string, using a stack.

        Elements must be separated by spaces.
        Display progress on screen.
    """
    tokenlist = string.split()
    stack = Stack()
    for token in tokenlist:
        print('next token taken from string is', token)
        if token in ["+", "-", "*", "/"]:
            second = stack.pop()
            first = stack.pop()
            print('   Op, so pop twice, and evaluate <2nd-top> <op> <top>',
                  first, token, second)
            if token == "+":
                print('    = ', first + second)
                stack.push(first + second)
            elif token == "-":
                print('    = ', first - second)
                stack.push(first - second)
            elif token == "*":
                print('    = ', first * second)
                stack.push(first * second)
            else:
                print('    = ', first / second)
                stack.push(first / second)
            print('   and push back onto stack')
        else:
            print('   Value (=', token, ') so push onto stack')
            stack.push(int(token))
        print('Stack is now:', stack)
    print('No tokens left in string, so pop from stack (of length 1):', stack)
    return stack.pop()
Ejemplo n.º 13
0
def correctBracket(givenString):
    charStack = Stack()
    for char in givenString:
        if char == '{' or char == '[' or char == '(':
            charStack.push(char)
        elif char == '}':
            if charStack.top() != '{':
                return 'INCORRECT'
            charStack.pop()
        elif char == ']':
            if charStack.top() != '[':
                return 'INCORRECT'
            charStack.pop()
        elif char == ')':
            if charStack.top() != '(':
                return 'INCORRECT'
            charStack.pop()
    return 'ITS CORRECT'
Ejemplo n.º 14
0
def reverseStack(givenStack):
    newStack = Stack()
    while givenStack.length() != 0: #& isinstance(obj, stackA):
        newStack.push(givenStack.pop())
    return newStack
Ejemplo n.º 15
0
def infixConverter(equationString):
    numStack = Stack()
    numList = []
#     operatorValues = {"/":2, "*":2, "+":1, "-":1}
    
    for variable in equationString:
        try: 
            int(variable)
            numList.append(variable)
        except ValueError:
            if variable == "(":
                numStack.push(variable)
            elif variable == ")":
                while numStack.top() != "(":
                    numList.append(numStack.pop())
                numStack.pop()
            elif (variable == "*" or variable == "/"):
                if numStack.top() == "*" or numStack.top() == "/":
                    numList.append(numStack.pop())
                    numStack.push(variable)
                else:
                    numStack.push(variable)
            elif (variable == "+" or variable == "-"):
                numStack.push(variable)
    while numStack.length() != 0:
        numList.append(numStack.pop())
    s = " "
    print(s.join(numList)) 
Ejemplo n.º 16
0
'''
Created on 28 Sep 2018

@author: cm80
'''
import stackA
from stackA import Stack
import random
from random import randint
import sys 
import time
from _ast import operator

givenStack = Stack()

givenStack.push('C')
givenStack.push('H')
givenStack.push('A')
givenStack.push('D')
givenStack.push('M')
givenStack.push('O')
givenStack.push('R')
givenStack.push('R')
givenStack.push('O')
givenStack.push('W')

givenString = '()(6+5){6[5(4+3)]})'

def reverseStack(givenStack):
    newStack = Stack()
    while givenStack.length() != 0: #& isinstance(obj, stackA):