def toBinary(num): s = Stack() while num > 0: s.push(str(num % 2)) num = num // 2 dataList = [s.pop() for x in range(s.size())] return "".join(dataList)
def divideBy2(decNumber): """ decimal to binary. :param decNumber: :return: """ s = Stack() while decNumber > 0: s.push(decNumber % 2) decNumber = decNumber // 2 return ''.join(str(s.pop()) for i in range(s.size()))
def inorderTrav(tree): posStack = Stack() current = tree while current != None or posStack.size() > 0: # Left-most node while (current != None): posStack.push(current) current = current.getLeftChild() current = posStack.pop() print(current.getRootVal()) current = current.getRightChild()
def postfixEval(postfixExpr): operandStack = Stack() tokenList = [char for char in postfixExpr] # DA_20_20 mod for token in tokenList: if token in "0123456789": operandStack.push(int(token)) elif token in "*/+-" and operandStack.size( ) > 1: # DA_20_20 handle errors mod operand2 = operandStack.pop() operand1 = operandStack.pop() result = doMath(token, operand1, operand2) operandStack.push(result) return operandStack.pop()
def baseConverter(decNumber, base): """ decimal to binary. :param decNumber: :return: """ digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' s = Stack() while decNumber > 0: s.push(decNumber % base) decNumber = decNumber // base return ''.join(digits[s.pop()] for i in range(s.size()))
def converter(number: int, base: int) -> str: """进制转换,支持十进制转换为2~16进制""" if not (isinstance(number, int) and isinstance(base, int)): raise TypeError('type must be both int') if not 2 <= base <= 16: raise ValueError('base must be among 2 and 16') if number < 0: raise ValueError('the number must be larger than 0') if number == 0: return '0' s = Stack() num_to_alp = {10: 'A', 11: 'B', 12: 'C', 13: 'D', 14: 'E', 15: 'F'} while number != 0: remainder = number % base if remainder in num_to_alp.keys(): s.push(num_to_alp[remainder]) else: s.push(remainder) number //= base res = '' for i in range(s.size()): res += str(s.pop()) return res
from pythonds.basic import Stack s = Stack() print(s.isEmpty()) s.push(4) s.push('dog') print(s.peek()) s.push(True) print(s.size()) print(s.isEmpty()) s.push(8.4) print(s.pop()) print(s.pop()) print(s.size())
def build_parse_tree(self): token_lst = self.parse_expr.parse_expression(self.expr, self.variables) stack = Stack() tree = BinaryTreeExtended('') stack.push(tree) current_tree = tree idx = 0 while idx < len(token_lst): token = token_lst[idx] if token == '(': current_tree.insertLeft('') stack.push(current_tree) current_tree = current_tree.getLeftChild() idx += 1 elif token in set(self.terms.binops) | {'-'}: # node already has value so tree needs to be extended if current_tree.getRootVal(): if stack.size() == 1: tree = BinaryTreeExtended('') tree.insertLeftExistingTree(current_tree) current_tree = tree else: current_child = current_tree.getLeftChild() new_child = BinaryTreeExtended('') new_child.insertLeftExistingTree(current_child) current_tree.insertLeftExistingTree(new_child) stack.push(current_tree) current_tree = current_tree.getLeftChild() if token in self.terms.binops: current_tree.setRootVal(token) current_tree.insertRight('') stack.push(current_tree) current_tree = current_tree.getRightChild() idx += 1 elif token == '-': # '-' should be treated as a minus sign if current_tree.getLeftChild(): current_tree.setRootVal(token) current_tree.insertRight('') stack.push(current_tree) current_tree = current_tree.getRightChild() idx += 1 # '-' should be treated as a negation elif not token_lst[idx + 1].isdigit() and not token_lst[ idx + 1] in self.variables: current_tree.setRootVal('neg') current_tree.insertLeft('') stack.push(current_tree) current_tree = current_tree.getLeftChild() idx += 1 # '-' should be treated as a negative number else: current_tree.setRootVal('*') current_tree.insertRight('') stack.push(current_tree) current_tree = current_tree.getRightChild() current_tree.setRootVal('-' + token_lst[idx + 1]) idx += 2 parent = stack.pop() current_tree = parent current_tree.insertLeft('') stack.push(current_tree) current_tree = current_tree.getLeftChild() else: raise ValueError elif token == ')': current_tree = stack.pop() idx += 1 elif token in self.terms.unop2operator: current_tree.setRootVal(token) idx += 1 elif token.isnumeric() or token in self.variables: current_tree.setRootVal(token) parent = stack.pop() current_tree = parent idx += 1 else: raise ValueError self.parse_tree = tree
path.pop() startNode.setColor('white') else: done = True return done # Warnsdorff启发式算法 def orderByAvail(depthNode): resList = [] for v in list(depthNode.getConnections()): if v.getColor() == 'white': c = 0 for w in list(v.getConnections()): if w.getColor() == 'white': c += 1 resList.append((c, v)) resList.sort(key=lambda x: x[0]) return [y[1] for y in resList] if __name__ == '__main__': graph = knightGraph(8) path = Stack() startVert = graph.getVertex(4) knightTour(0, path, startVert) idList = [] for i in range(path.size()): idList.append(path.pop().getId()) print(idList[::-1])
def revstring(mystr): s = Stack() for each in mystr: s.push(each) result = ''.join(s.pop() for i in range(s.size())) print(result)
from pythonds.basic import Stack s = Stack() print(s.isEmpty()) s.push(4) s.push('dog') print(s.peek()) # dog print(s.pop()) # dog print(s.size(), s.items) print('dfsdf %s' % 'xxx')
class ASM_COMPLEX_IF(): args_list = [] reserved_bool1 = 0 reserved_bool2 = 0 stack_args = '' list_completed = [] formed_code = '' target_if_true = '' target_if_false = '' def __init__(self, args_list, target_if_true, target_if_false): self.args_list = args_list self.target_if_true = target_if_true self.target_if_false = target_if_false # init a empty stack self.stack_args = Stack() # insert each value in the args list into the stack for item in self.args_list[::-1]: self.stack_args.push(item) def detect_conditions(self, cmp): return conditions[cmp] def detect_contrary(self, cmp): return contrary_conditions[cmp] def detect_bool_available(self): if self.reserved_bool1 == 0: self.reserved_bool1 = 1 return 'r_bool_1' if self.reserved_bool2 == 0: self.reserved_bool2 = 1 return 'r_bool_1' def get_params(self): # peek the value in the stack temp_op1 = '' temp_op2 = '' while self.stack_args.size() > 0: # peek the value found in stack curr_val = self.stack_args.peek() if curr_val not in operands: if temp_op1 == '': temp_op1 = self.stack_args.pop() if temp_op2 == '': temp_op2 = self.stack_args.pop() else: # FOUND A OPERAND op = self.stack_args.pop() # generate the if code based on the operand if op in rel_eq_op: # get the type of comparison and contrary cond = self.detect_conditions(op) contr = self.detect_contrary(cond) temp = self.detect_bool_available() # generate the template template = Template(if_complex['if_false']) # if reserved bool # replace the values in template template = template.safe_substitute(reg1 = temp_op1, reg2 = temp_op2, comp = cond, temp = temp, contr = contr, t_false = self.target_if_false) # append to the completed code self.formed_code = self.formed_code + template # IF IN CASE NOT IN THE BASIC OPERANDS IT IS && OR || else: # DOESNT DO ANYTHING UP TO NOW op = 0 # test area # a = ASM_COMPLEX_IF(['r2', 'r1', '>', 'r1', 'r2', '==', '&&', 'sucasa', 'ddfa', '>', '||']) # a.get_params()