def stack_split_alt(source): """ ------------------------------------------------------- Splits the source stack into separate target stacks. When finished source stack is empty. Values are pushed alternately onto the returned target stacks. Use: target1, target2 = stack_split_alt(source) ------------------------------------------------------- Parameters: source - the stack to split into two parts (Stack) Returns: target1 - contains alternating values from source (Stack) target2 - contains other alternating values from source (Stack) ------------------------------------------------------- """ target1 = Stack() target2 = Stack() i = 1 while source.is_empty() == False: if i == 1: target1.push(source.pop()) i = 2 elif i == 2: target2.push(source.pop()) i = 1 return target1, target2
def postfix(string): """ ------------------------------------------------------- Evaluates a postfix expression. Use: answer = postfix(string) ------------------------------------------------------- Parameters: string - the postfix string to evaluate (str) Returns: answer - the result of evaluating string (float) ------------------------------------------------------- """ string = string.split(" ") r = Stack() for i in string: if i.isdigit(): r.push(i) elif i in OPERATORS: if i == "+": r.push(float(r.pop()) + float(r.pop())) elif i == "-": x = float(r.pop()) y = float(r.pop()) r.push(y - x) elif i == "*": r.push(float(r.pop()) * float(r.pop())) elif i == "/": r.push(float(r.pop()) / float(r.pop())) answer = r.pop() return answer
def stack_combine(source1, source2): """ ------------------------------------------------------- Combines two source stacks into a target stack. When finished, the contents of source1 and source2 are interlaced into target and source1 and source2 are empty. Use: target = stack_combine(source1, source2) ------------------------------------------------------- Parameters: source1 - a stack (Stack) source2 - another stack (Stack) Returns: target - the contents of the source1 and source2 are interlaced into target (Stack) ------------------------------------------------------- """ target = Stack() i = 1 while source1.is_empty() == False or source2.is_empty() == False: if i == 1: target.push(source1.pop()) if source2.is_empty() == False: i = 2 elif i == 2: target.push(source2.pop()) if source1.is_empty() == False: i = 1 return target
def stack_test(source): """ ------------------------------------------------------- Tests the methods of Stack for empty and non-empty stacks using the data in source: is_empty, push, pop, peek (Testing pop and peek while empty throws exceptions) Use: stack_test(source) ------------------------------------------------------- Parameters: source - list of data (list of ?) Returns: None ------------------------------------------------------- """ stack = Stack() print('Test is empty?') print(stack.is_empty()) print(array_to_stack(stack, source)) print('Test is empty?') print(stack.is_empty()) print('Test for peek value: ') print(stack.peek()) print('Test for push value: ') stack.push(1) print('Test for peek value: ') print(stack.peek()) print('Test for pop value: ') stack.pop() print('Test is empty?') print(stack.is_empty()) print('Test for peek value: ') print(stack.peek())
def mirror(string): b = True stack = Stack() n = len(string) i = 0 while b and string[i] != MID: if string[i] in CHARS: stack.push(string[i]) i += 1 else: b = False i += 1 # Skip MID while b and i < n: if stack.is_empty(): b = False else: c = stack.pop() if not c == string[i]: b = False else: i += 1 return b
def is_palindrome_stack(string): """ ------------------------------------------------------- Determines if string is a palindrome. Ignores case, digits, spaces, and punctuation in string. Use: palindrome = is_palindrome_stack(string) ------------------------------------------------------- Parameters: string - a string (str) Returns: palindrome - True if string is a palindrome, False otherwise (bool) ------------------------------------------------------- """ palindrome = None newstr = "" s = Stack() for i in string: if i.isalnum(): newstr += i for j in newstr: s.push(j) revstr = "" for k in s: revstr += s.pop() if revstr.lower() == newstr.lower(): palindrome = True else: palindrome = False return palindrome
def postfix(string): """ ------------------------------------------------------- Evaluates a postfix expression. Use: answer = postfix(string) ------------------------------------------------------- Parameters: string - the postfix string to evaluate (str) Returns: answer - the result of evaluating string (float) ------------------------------------------------------- """ s = Stack() ss = string.split() for i in ss: if i.isdigit(): s.push(i) elif i in OPERATORS: val1 = s.pop() val2 = s.pop() if i == "+": s.push(float(int(val2) + int(val1))) elif i == "-": s.push(float(int(val2) - int(val1))) elif i == "*": s.push(float(int(val2) * int(val1))) elif i == "/": s.push(float(int(val2) / int(val1))) answer = s.pop() return answer
def stack_test(source): """ ------------------------------------------------------- Tests the methods of Stack for empty and non-empty stacks using the data in source: is_empty, push, pop, peek (Testing pop and peek while empty throws exceptions) Use: stack_test(source) ------------------------------------------------------- Parameters: source - list of data (list of ?) Returns: None ------------------------------------------------------- """ s = Stack() # Test if stack is empty (Expected: TRUE) print("Stack contents: ") for i in s: print(i, end=' ') print("\tEmpty? {}".format(s.is_empty())) # Load elements from source into Stack print(">> Push elements from source onto stack") print(">> Num elements to push: {}".format(len(source))) for elem in source: s.push(elem) # Check if the Stack is empty again (T/F depending on source contents) print("Stack contents: ") for i in s: print(i, end=' ') print("\tEmpty? {}".format(s.is_empty())) # Peek the top of the stack top = None try: top = s.peek() except: print(">>! Peeked at an empty stack, assertion caught, continuing...") # Check if top of stack is the end element of source print("Top of stack should be same as end of list") if s.is_empty(): print("List empty so no check") else: top_same = top == source[-1] print("Top same as end of list?") print("Top: {}\tEnd of list: {}".format(top, source[-1])) print("Same? {}".format(top_same)) # Testing pop try: print(">> Pop top of stack") popped = s.pop() print("Popped value should be same as end of list.\tSame? {}".format(popped == source[-1])) except: print(">>! Popped from an empty stack, exception caught, continuing...") return
def stack_test(source): """ ------------------------------------------------------- Tests the methods of Stack for empty and non-empty stacks using the data in source: is_empty, push, pop, peek (Testing pop and peek while empty throws exceptions) Use: stack_test(source) ------------------------------------------------------- Parameters: source - list of data (list of ?) Returns: None ------------------------------------------------------- """ s = Stack() print("Stack Initialised") print() print(SEP) print("Stack is_empty (expect True): {}".format(s.is_empty())) print(SEP) print("Add one item to Stack:") s.push(source[0]) print("Top of Stack (peek):") print(s.peek()) print(SEP) print("Stack is_empty (expect False): {}".format(s.is_empty())) print(SEP) print("Stack pop:") v = s.pop() print(v) print(SEP) print("Stack is_empty (expect True): {}".format(s.is_empty())) print(SEP) print("Copy all data to Stack") array_to_stack(s, source) print(SEP) print("Stack is_empty (expect False): {}".format(s.is_empty())) print(SEP) print("Top of Stack (peek):") print(s.peek()) print(SEP) print("Remove all elements from Stack") while not s.is_empty(): v = s.pop() print(v) print() print(SEP) print("Stack is_empty (expect True): {}".format(s.is_empty())) print() return
def stack_maze(maze): """ ------------------------------------------------------- Solves a maze using Depth-First search. Use: path = stack_maze(maze) ------------------------------------------------------- Parameters: maze - dictionary of points in a maze, where each point represents a corridor end or a branch. Dictionary keys are the name of the point followed by a list of branches, if any. First point is named 'Start', exit is named 'X' (dict) Returns: path - list of points visited before the exit is reached, None if there is no exit (list of str) ------------------------------------------------------- """ s = Stack() wrongpath = [] value = maze['Start'] exfi = False for i in maze: if 'X' in maze[i]: path = [] exfi = False elif exfi != False: path = None if path != None: for i in value: s.push(i) value = s.pop() path.append(value) while value != 'X' and path != None: value = maze[value] while len(value) == 0: value = s.pop() for i in value: if i in path: _index = path.index(i) wrongpath = path[_index + 1:] path = path[:_index] s.push(i) value = s.pop() path.append(value) if value in wrongpath: value = s.pop() return path
def main(): source1 = Stack() source2 = Stack() l = [8, 12, 8, 5] for v in l: source1.push(v) l2 = [14, 9, 7, 1, 6, 3] for x in l2: source2.push(x) target = stack_combine(source1, source2) for t in target: print(t)
def main(): source1 = Stack() source2 = Stack() l = [8,12,8,5] for v in l: source1.push(v) l2 = [14,9,7,1,6,3] for x in l2: source2.push(x) stack = Stack() stack.combine(source1, source2) for s in stack: print(s)
def has_balanced_brackets(string): """ ------------------------------------------------------- Determines if a string contains balanced brackets or not. Non-bracket characters are ignored. Uses a stack. Brackets include {}, [], (), <>. Use: balanced = has_balanced_brackets(string) ------------------------------------------------------- Parameters: string - the string to test (str) Returns: balanced (int) - BALANCED if the brackets in string are balanced MISMATCHED if the brackets in string are mismatched MORE_RIGHT if there are more right brackets than left in string MORE_LEFT if there are more left brackets than right in string ------------------------------------------------------- """ right = 0 left = 0 s = Stack() for x in string: if s.is_empty() == True: s.push(x) elif s.peek() == '[' and x == ']' or s.peek( ) == '(' and x == ')' or s.peek() == '{' and x == '}' or s.peek( ) == '<' and x == '>': s.pop() else: s.push(x) if s.is_empty() == True: balanced = 0 else: while s.is_empty() == False: x = s.pop() if x == '(' or x == '[' or x == '{' or x == '<': left += 1 elif x == ')' or x == ']' or x == '}' or x == '>': right += 1 if right > left: balanced = 2 elif left > right: balanced = 1 else: balanced = 3 return balanced
def has_balanced_brackets(string): """ ------------------------------------------------------- Determines if a string contains balanced brackets or not. Non-bracket characters are ignored. Uses a stack. Brackets include {}, [], (), <>. Use: balanced = has_balanced_brackets(string) ------------------------------------------------------- Parameters: string - the string to test (str) Returns: balanced (int) - BALANCED if the brackets in string are balanced MISMATCHED if the brackets in string are mismatched MORE_RIGHT if there are more right brackets than left in string MORE_LEFT if there are more left brackets than right in string ------------------------------------------------------- """ s = Stack() balanced = BALANCED OPEN_BRACKETS = "([{<" CLOSING_BRACKETS = ")]}>" char_index = 0 while balanced == BALANCED and char_index < len(string): # Get current character we are processing char = string[char_index] if char in OPEN_BRACKETS: # Push any opening bracket we see onto the stack s.push(char) elif char in CLOSING_BRACKETS: # Check if top of stack matches closing brackets if s.is_empty(): # If stack is empty but we see a closing bracket balanced = MORE_RIGHT else: top = s.pop() # Get index of bracket at top of stack in OPEN_BRACKETS index = 0 for i in range(len(OPEN_BRACKETS)): if top == OPEN_BRACKETS[i]: index = i # Index of closing bracket should be same as open bracket complimentary_bracket = CLOSING_BRACKETS[index] if not char == complimentary_bracket: balanced = MISMATCHED char_index += 1 if not s.is_empty(): # If we still have opening brackets in the stack but we reach the end of the string balanced = MORE_LEFT return balanced
def stack_test(source): """ ------------------------------------------------------- Tests the methods of Stack for empty and non-empty stacks using the data in source: is_empty, push, pop, peek (Testing pop and peek while empty throws exceptions) Use: stack_test(source) ------------------------------------------------------- Parameters: source - list of data (list of ?) Returns: None ------------------------------------------------------- """ stack = Stack() dummy = [] if stack.is_empty() == True: print('Stack is empty.') array_to_stack(stack, source) print('Converting source into a stack...') if stack.is_empty() == False: print('source has been transferred into stack!') print('\nPopping stack...') while stack.is_empty() == False: temp = stack.pop() print(temp) dummy.append(temp) print('\nstack is empty. Pushing values back into stack...') while dummy != []: temp = dummy.pop() print(temp) stack.push(temp) print('\nPushing complete! Peeking...') print(stack.peek()) return
def stack_combine(source1, source2): """ ------------------------------------------------------- Combines two source stacks into a target stack. When finished, the contents of source1 and source2 are interlaced into target and source1 and source2 are empty. Use: target = stack_combine(source1, source2) ------------------------------------------------------- Parameters: source1 - a stack (Stack) source2 - another stack (Stack) Returns: target - the contents of the source1 and source2 are interlaced into target (Stack) ------------------------------------------------------- """ # Determine which stack is the shortest, going to loop over that #shortest_stack = source2 if len(source1) > len(source2) else source1 shortest_stack = None other_stack = None if len(source1) > len(source2): shortest_stack = source2 other_stack = source1 else: shortest_stack = source1 other_stack = source2 target = Stack() # Loop and append until shortest stack is empty while not shortest_stack.is_empty(): val1 = shortest_stack.pop() val2 = other_stack.pop() target.push(val1) target.push(val2) # Handle the rest of the elements in the longer stack for element in other_stack: target.push(element) return
def stack_test(source): """ ------------------------------------------------------- Tests the methods of Stack for empty and non-empty stacks using the data in source: is_empty, push, pop, peek (Testing pop and peek while empty throws exceptions) Use: stack_test(source) ------------------------------------------------------- Parameters: source - list of data (list of ?) Returns: None ------------------------------------------------------- """ s = Stack() array_to_stack(s, source) print(s.is_empty()) print(s.peek()) print(s.pop()) s.push(1) return
def postfix(string): """ ------------------------------------------------------- Evaluates a postfix expression. Use: answer = postfix(string) ------------------------------------------------------- Parameters: string - the postfix string to evaluate (str) Returns: answer - the result of evaluating string (float) ------------------------------------------------------- """ s = Stack() expression = string.split(" ") # Split on spaces for char in expression: if char in OPERATORS: # Order that we pop is important operand2 = s.pop() operand1 = s.pop() if char == OPERATORS[0]: # Addition value = operand1 + operand2 elif char == OPERATORS[1]: # Subtraction value = operand1 - operand2 elif char == OPERATORS[-2]: # Multiplication value = operand1 * operand2 elif char == OPERATORS[-1]: # Division, do not have to worry about division by zero value = operand1 / operand2 s.push(value) else: # Dealing with a numeric value s.push(int(char)) answer = s.pop() # Answer should be the only thing left in the stack return answer
def is_palindrome_stack(string): """ ------------------------------------------------------- Determines if string is a palindrome. Ignores case, spaces, and punctuation in string. Use: palindrome = is_palindrome_stack(string) ------------------------------------------------------- Parameters: string - a string (str) Returns: palindrome - True if string is a palindrome, False otherwise (bool) ------------------------------------------------------- """ r = 1 s_4 = Stack() string1 = string for x in ' ,.!?': string1 = string1.replace(x, '') string1 = string1.lower() if (len(string1) % 2) == 0: for x in string1: if s_4.is_empty() == True: s_4.push(x) else: y = s_4.pop() if x != y: s_4.push(y) s_4.push(x) else: half = (len(string1) / 2) + 0.5 for x in string1: if r < half: s_4.push(x) elif r > half: y = s_4.pop() if x != y: s_4.push(y) r += 1 if s_4.is_empty() == True: palindrome = True else: palindrome = False return palindrome
from Stack_array import Stack values = [1, 2, 3, 4] print("Values: {}".format(values)) s = Stack() print(">> Is the stack empty?") empty = s.is_empty() print("Expect: {}\tGot: {}".format(True, empty)) print(">> Pushing values onto Stack") for val in values: s.push(val) print("Stack contents: ", end='') print("Expect: {}\tGot: ".format(values[::-1]), end='') for elem in s: print(elem, end=' ') print() print(">> Pop top of stack") value = s.pop() print("Expect: {}\tGot: {}".format(values[-1], value)) print(">> Peek the top of the stack") peeked = s.peek() print("Expect: {}\tGot: {}".format(values[-2], peeked))
Lab 2, Task 3 - utilities#stack_to_array ------------------------------------------------------------------------ Author: Nicolas Mills ID: 180856100 Email: [email protected] __updated__ = 2019-01-21 ------------------------------------------------------------------------ """ from utilities import stack_to_array from Stack_array import Stack target = [] array = [1, 2, 3, 4] s = Stack() for i in array: s.push(i) print("Array before: {}".format(target)) print("Stack before:") for i in s: print(i, end=' ') print() stack_to_array(s, target) print("Array after: {}".format(target)) print("Stack After:") for i in s: print(i, end=' ')