示例#1
0
def match_parenthesis (symbolString):
  ## close any and all open parenthesises & return a "file" to be processed further... 
  from pythonds.basic.stack import Stack
  s = Stack()
  balanced = True
  index = 0
  while index < len(symbolString) and balanced:
        symbol = symbolString[index]
        if symbol == "(":
            s.push(symbol+ str(index))
        elif symbol == ")":
            if s.isEmpty():
                balanced = False
            else:
                s.pop()

        index = index + 1

  if balanced and s.isEmpty():
        #print ("it is FINALLY balanced!")
        return symbolString
  elif balanced and not s.isEmpty():
        #print "opening barace is not closed at " 
        
        idx = int (s.pop().strip("("))
        #print idx
        #print symbolString[idx]
        return (match_parenthesis(removeExtra(symbolString,idx))) 
  else:   #couldn't pop from stack
        #print "extra closing present at"
        #print index
        return (match_parenthesis(removeExtra(symbolString,index-1))) 
示例#2
0
def infixToPostfix(infixexpr):
	prec = {'^': 4, '*': 3, '/': 3, '+': 2, '-': 2, '(': 1}
	opStack = Stack()
	postfixList = []
	tokenList = infixexpr.split()

	for token in tokenList:
		if token in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' or token in '1234567890':
			postfixList.append(token)

		elif token == '(':
			opStack.push('(')
		elif token == ')':
			topToken = opStack.pop()
			while topToken != '(':
				postfixList.append(topToken)
				topToken = opStack.pop()
		else:
			while (not opStack.isEmpty() ) and (prec[opStack.peek()] >= prec[token]):
				postfixList.append(opStack.pop())
			opStack.push(token)

	while not opStack.isEmpty():
		postfixList.append(opStack.pop())
	return ''.join(postfixList)
def parChecker(symbolString):
	s = Stack()
	balanced = True
	index = 0

	while index < len(symbolString) and balanced:
		symbol = symbolString[index]

		if symbol in "({[":
			s.push(symbol)

		else:
			if s.isEmpty():
				balanced = False

			else:
				top = s.pop()
				if not matches(top,symbol):
					balanced = False

		index = index + 1


	if balanced and s.isEmpty():
		return True
	else:
		return False
示例#4
0
def infixToPostfix(infixexpr):
    prec = {}
    prec["*"] = 3
    prec["/"] = 3
    prec["+"] = 2
    prec["-"] = 2
    prec["("] = 1
    opStack = Stack()
    postfixList = []
    tokenList = infixexpr.split()

    for token in tokenList:
        if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789":
            postfixList.append(token)
        elif token == '(':
            opStack.push(token)
        elif token == ')':
            topToken = opStack.pop()
            while topToken != '(':
                postfixList.append(topToken)
                topToken = opStack.pop()
        else:
            while (not opStack.isEmpty()) and \
               (prec[opStack.peek()] >= prec[token]):
                  postfixList.append(opStack.pop())
            opStack.push(token)

    while not opStack.isEmpty():
        postfixList.append(opStack.pop())
    return " ".join(postfixList)
示例#5
0
def parse_num(list):
    no_operator = re.split(r'[(+)notandor]', list)
    no_operator = [i for i in no_operator if i != '']
    no_operand = re.split(r'[0123456789]', list)
    no_oper = []
    parsed = []
    p = Stack()
    count = 0
    for i in range(len(no_operand)):
        if no_operand[i] == "(":
            p.push(no_operand[i])
        if no_operand[i] in ['+', '-', '*', '/', ')', 'not', 'and', 'or']:
            if p.peek() != '':
                p.push('')
                p.push(no_operand[i])
            else:
                p.push(no_operand[i])
        if no_operand[i] == '':
            if p.peek() != '':
                p.push('')

    no_oper = p.items

    for i in range(len(no_oper)):
        if no_oper[i] != '':
            parsed.append(no_oper[i])
        else:
            parsed.append(no_operator[count])
            count += 1
    return parsed
def infixToPostfix(infixexpr):
    prec = {'*': 3, '/': 3, '+': 2, '-': 2, '(': 1, '^': 4}
    postfixList = []
    opStack = Stack()

    tokenList = infixexpr.split()
    for token in tokenList:
        if token in string.uppercase or token.isdigit():
            postfixList.append(token)
        elif token == '(':
            opStack.push(token)
        elif token == ')':
            top = opStack.pop()
            while top != '(':
                postfixList.append(top)
                top = opStack.pop()
        else:
            while not opStack.isEmpty() and prec[opStack.peek()] >= prec[token]:
                postfixList.append(opStack.pop())
            opStack.push(token)

    while not opStack.isEmpty():
        postfixList.append(opStack.pop())

    return " ".join(postfixList)
示例#7
0
def infixToPostfix(infixexpr):
   prec = {}
   prec["^"] = 4
   prec["*"] = 3
   prec["/"] = 3
   prec["+"] = 2
   prec["-"] = 2
   prec["("] = 1
   opStack = Stack()
   postfixList = []
   tokenList = infixexpr.split()

   for token in tokenList:
      if token in string.ascii_uppercase or token in string.digits:
         postfixList.append(token)
      elif token == "(":
         opStack.push(token)
      elif token == ")":
         topToken = opStack.pop()
         while topToken != "(":
            postfixList.append(topToken)
            topToken = opStack.pop()

      else:
         while (not opStack.isEmpty()) and (prec[opStack.peek()] >= prec[token]):
            postfixList.append(opStack.pop())
         opStack.push(token)

   while not opStack.isEmpty():
      postfixList.append(opStack.pop())
   return " ".join(postfixList)
示例#8
0
def match_parenthesis(symbolString):
    ## close any and all open parenthesises & return a "file" to be processed further... 
    from pythonds.basic.stack import Stack
    s = Stack()
    balanced = True
    index = 0
    while index < len(symbolString) and balanced:
        symbol = symbolString[index]
        if symbol == "(":
            s.push(symbol+ str(index))
        elif symbol == ")":
            if s.isEmpty():
                balanced = False
            else:
                s.pop()

        index = index + 1

    if balanced and s.isEmpty():
        return symbolString
    elif balanced and not s.isEmpty():
        idx = int (s.pop().strip("("))
        return (match_parenthesis(removeExtra(symbolString,idx)))
    else:   #couldn't pop from stack
        return (match_parenthesis(removeExtra(symbolString,index-1)))
 def infix_to_postfix(self, infixexpr):
     opStack = Stack()
     postfixList = []
     tokenList = infixexpr.split()
     
     for token in tokenList:
         if BoolParser.isBoolVariable(token):
             # if token is a boolean variable, just append to list
             postfixList.append(token)
         elif token == '(':
             # start a new nested expression in the stack
             opStack.push(token)
         elif token == ')':
             # end the nested expression by moving the operators
             # from the stack to the list (i.e. in reverse order)
             topToken = opStack.pop()
             while topToken != '(':
                 postfixList.append(topToken)
                 topToken = opStack.pop()
         else:
             while (not opStack.isEmpty()) and \
                (BoolParser.PREC[opStack.peek()] >= BoolParser.PREC[token]):
                   postfixList.append(opStack.pop())
             opStack.push(token)
 
     while not opStack.isEmpty():
         postfixList.append(opStack.pop())
     
     return postfixList
示例#10
0
	def chkid_allrecord(self,m,rr1):
			# que = "SELECT * FROM wp_2015ptainsuracelist where frm_id='%s';" % (rr1)
			# rr=m.db.query(que)
			idData = (str(rr1),)
			que = """SELECT * FROM """+self.table+""" where frm_id==?"""
			rr=m.dbsql3.data_query(que,idData,False)
			print rr
			p = Stack()
			print(rr)
			if rr:
				for i in rr[0]:
					p.push(i)
				rrr=p.seek()
				OR = rrr[18]
				ins = rrr[16]
				reg = rrr[15]
				trans = rrr[19]
				print "Pass chkid_allrecord!******************"
				if OR=='' and ins==0 and reg==0 and trans=='':
					return 'False1',rrr
				if OR!='' and ins==0 and trans!='':
					return 'True1',rrr
				if OR!='' and ins!=0 and trans!='':
					return 'True2',rrr
			else:
				return 'False2'
示例#11
0
	def chkid_len(self,main,a,b=None,c=None,d=None,e=False):

		if e:
			if len(a)==8 or len(a)==10 or a.count('x')==4:
				return True
			else:
				self.alert(main,'ID Less than 8 or 10!','ID length allowed is 8 or 10 \n You have #'+str(len(a))+' digits.')
				return False
		else:
			print("self table===="+self.table)
			print("Check by name is activated!")
			# que = "SELECT * FROM wp_2015ptainsuracelist where frm_stdname='%s' AND frm_std_middle_name='%s' AND frm_std_last_name='%s';" % (b,c,d)
			que = """SELECT * FROM """+self.table+""" where frm_stdname=? AND frm_std_middle_name=? AND frm_std_last_name=?"""
			fullname = (str(b),str(c),str(d))
			rr=main.dbsql3.data_query(que,fullname)
			p = Stack()
			print(b+" "+c+" "+d)
			print("student name! search")
			print(rr)
			if rr:
				for i in rr[0]:
					p.push(i)
				rrr=p.seek()
				OR = rrr[18]
				ins = rrr[16]
				reg = rrr[15]
				trans = rrr[19]
				if OR=='' and ins==0 and reg==0 and trans=='':
					return 'False1'
				if OR!='' and ins==0 and trans!='':
					return 'True1',rrr
				if OR!='' and ins!=0 and trans!='':
					return 'True2',rrr
			else:
				return 'False2'
def infixToPostfix(infixexpr):
    prec = {}
    prec['*'] = 3
    prec['/'] = 3
    prec['+'] = 2
    prec['-'] = 2
    prec['('] = 1
    opStack = Stack()
    postfixList = []
    tokenList = infixexpr.split()

    for token in tokenList:
        if token in 'ABCDEFGHIJKLMNOPQRSTUMWXYZ' or token in '0123456789':
            postfixList.append(token)
        elif token == '(':
            opStack.push(token)
        elif token == ')':
            topToken = opStack.pop()
            while topToken != '(':
                postfixList.append(topToken)
                topToken = opStack.pop()
        else:
            while (not opStack.isEmpty()) and (prec[opStack.peek()] >= prec[token]):
                postfixList.append(opStack.pop())
            opStack.push(token)

    while not opStack.isEmpty():
        postfixList.append(opStack.pop())

    return ' '.join(postfixList)
示例#13
0
def revstring(mystr):
	s = Stack()
	new_mystr = ''
	for i in mystr:
		s.push(i)
	while not s.isEmpty():
		new_mystr = new_mystr+s.pop()
	return new_mystr
def sortstacks(astack):
     temp=Stack()
     while not astack.isEmpty():
          tmp=astack.pop()
          while temp.peek()<tmp:
               temp.pop()
          temp.push(tmp)
     return temp
示例#15
0
def revstring(mystr):
    myStack = Stack()
    for i in mystr:
      myStack.push(i)
      revstr = ''
    while not myStack.isEmpty():
      revstr = revstr + myStack.pop()
    return revstr
示例#16
0
def revstring_mine(mystr):
    s = Stack()
    for char in mystr:
        s.push(char)
    revstr = ''
    while not s.isEmpty():
        revstr += s.pop()
    return revstr
class Conversion (object) :
    
    def __init__(self):
        self.prec = {}
        self.init_prec()
        self.op_stack = Stack() #operators will be kept in this stack
        self.output_list = []   #any postfix or prefix expression will be written in the list
        self.token_list = [] #initial expression will be read and kept in this list    
        self.operands = []
        self.init_operand()
        
    def init_prec(self) :
        self.prec["*"] = 3
        self.prec["/"] = 3
        self.prec["+"] = 2
        self.prec["-"] = 2
        self.prec["("] = 1
    
    def init_operand(self) :
        self.operands = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "0123456789"
    
    def re_init(self) :
        #After any operation, the stack should be empty
        self.op_stack = Stack()
        self.output_list = []
        self.token_list = []

    def infixToPostfix(self,infixexpr) :
        '''The function will read an infix expression and write its 
        corresponding expression in the output_list
        doesn't return anything but alters the output_list'''
        self.re_init()
        self.token_list = infixexpr.split()
        for token in self.token_list :
            if token in self.operands :
                self.output_list.append(token)
            elif token == '(' :
                self.op_stack.push(token)
            elif token == ')' :
                top_token = self.op_stack.pop()
                while top_token != '(' :
                    self.output_list.append(top_token)
                    top_token = self.op_stack.pop()
            else :
                while (not self.op_stack.isEmpty()) and \
                    (self.prec[self.op_stack.peek()] >= self.prec[token]) :
                    self.output_list.append(self.op_stack.pop())
                self.op_stack.push(token)    
        while not self.op_stack.isEmpty() :
            self.output_list.append(self.op_stack.pop())             
    
    def getOutput(self) :
        return " ".join(self.output_list)

    def infixToPrefix(self, infixexpr) :
        pass
示例#18
0
def revstring(mystr):
    # your code here
    reversed = ""
    string_stack = Stack()
    for char in mystr:
        string_stack.push(char)
    while not string_stack.isEmpty():
        last = string_stack.pop()
        reversed += last
    return reversed
示例#19
0
文件: Parser.py 项目: haoxiang47/Mars
 def postfixEval(self, tokens):
     operandStack = Stack()
     for i in tokens:
         if i.isdigit():
             operandStack.push(int(i))
         else:
             operand2 = operandStack.pop()
             operand1 = operandStack.pop()
             result = self.compute(operand1, operand2, i)
             operandStack.push(result)
     return operandStack.pop()
def revString(astring):
    s = Stack() #create a new stack
    
    for ch in astring:
        s.push(ch)
    
    reverse_string = ''

    for i in range(len(astring)):
        reverse_string = reverse_string + s.pop()
        
    return reverse_string
示例#21
0
def divide_by_2(num):
    rem_stack = Stack() # putting my stack in action

    while num > 0:
        rem = num % 2 # remainder variable
        rem_stack.push(rem) # push the remainder in my stack
        num = num // 2 # divide my num by two

    bin_string = '' # create my binary string
    while not rem_stack.isEmpty():
        bin_string = bin_string + str(rem_stack.pop()) # pop the remainder from my stack
    return bin_string # get my binary string
示例#22
0
def postfixEval(postfixExpr):
	operandStack = Stack()
	tokenList = postfixExpr.split()

	for token in tokenList:
		if token in '0123456789':
			operandStack.push(int(token))
		elif token in '*/+-':
			num2 = operandStack.pop()
			num1 = operandStack.pop()
			operandStack.push(doMath(num1, num2, token))
	return operandStack.pop()
示例#23
0
def moveTower(height,fromPole, toPole, withPole):
	fromPole = Stack()
	toPole = Stack()
	withPole = Stack()
	for i in range(height):
		fromPole.push(i)
	if fromPole.size() == 1:
		Disk = fromPole.pop()
		toPole.push(Disk)
	else:
		moveTower(height-1, fromPole, toPole, withPole)
		print fromPole, toPole, withPole
示例#24
0
def divide_by2(dec_number):
    '''This function takes in a decimal number and converts it to a binary number'''
    rem_stack = Stack()

    while dec_number > 0:
        rem = dec_number % 2
        rem_stack.push(rem)
        dec_number = dec_number // 2

    bin_string = ''
    while not rem_stack.isEmpty():
        bin_string = bin_string + str(rem_stack.pop())
    return bin_string
示例#25
0
def base_convert(number, base):
    base_digits = '0123456789ABCDEF'
    base_stack = Stack()
    result = ''
    # 将需要转换的数字除以进制,余数为当前位的,商继续循环除以进制知道商为零
    while number:
        # 将余数作为下标在base_digits中取值,用以实现16进制
        current_number = base_digits[number % base]
        base_stack.push(current_number)
        number = number // base
    while not base_stack.isEmpty():
        result += str(base_stack.pop())
    return result
示例#26
0
def divideBy2(num):
    remStack = Stack()

    while num > 0:
        remStack.push(num % 2)

        num = num // 2

    binstring = ""
    while not remStack.isEmpty():
        binstring = binstring + str(remStack.pop())

    return binstring
def divide_by_two(decimal):
    stack = Stack()

    while decimal > 0:
        remainder = decimal % 2
        stack.push(remainder)
        decimal = decimal // 2

    binary = ''
    while not stack.isEmpty():
        binary += str(stack.pop())

    return binary
示例#28
0
def postfix(CalList):
    operandStack = Stack()
    tokenList = CalList.split()

    for token in tokenList:
        if token.isdigit():
            operandStack.push(int(token))
        else:
            operand2 = operandStack.pop()
            operand1 = operandStack.pop()
            result = doMath(token,operand1,operand2)
            operandStack.push(result)
    return operandStack.pop()
示例#29
0
def revstring(sg):
    s = Stack()

    lst = [i for i in sg]
    res = []

    for c in lst:
        s.push(c)

    while not s.isEmpty():
        res.append(s.pop())

    return "".join(res)
示例#30
0
def postfix_eval(postfixExpr):
    operandStack = Stack()
    tokenList = postfixExpr.split()

    for token in tokenList:
        if token.isdigit():
            operandStack.push(int(token))
        else:
            operand2 = operandStack.pop()
            operand1 = operandStack.pop()
            result = do_math(token, operand1, operand2)
            operandStack.push(result)
    return operandStack.pop()
示例#31
0
def postfixEval(postfixExpr):
    print(postfixExpr)
    operandStack = Stack()
    tokenList = postfixExpr.split()
    for token in tokenList:
        if is_float(token):
            operandStack.push(float(token))
        else:
            operand2 = operandStack.pop()
            operand1 = operandStack.pop()
            result = doMath(token, operand1, operand2)
            operandStack.push(result)
    return operandStack.pop()
示例#32
0
def evalPostFix(expr):
    expr = expr.split()

    opStack = Stack()

    for token in expr:
        if token in "0123456789":
            opStack.push(int(token))
        else:
            opB = opStack.pop()
            opA = opStack.pop()
            opStack.push(operate(token, opA, opB))
    return opStack.pop()
示例#33
0
def evaluate_postfix(postfixStr):
    evalStack = Stack()
    opList = postfixStr.split()

    for token in opList:
        if token.isalnum():
            evalStack.push(int(token))
        else:
            operand2 = evalStack.pop()
            operand1 = evalStack.pop()
            result = calculate(token, operand1, operand2)
            evalStack.push(result)
    return evalStack.pop()
class Queue:
    def __init__(self):
        self.inbox = Stack()
        self.outbox = Stack()

    def enqueue(self, item):
        self.inbox.push(item)

    def dequeue(self):
        if self.outbox.isEmpty():
            while (not self.inbox.isEmpty()):
                self.outbox.push(self.inbox.pop())
        return self.outbox.pop()
def evalPostfix(postfixExpr):
    operandStack = Stack()
    tokenList = postfixExpr.split()
    prec = {'*': 3, '/': 3, '+': 2, '-': 2, '(': 1}
    for token in tokenList:
        if token.isdigit():
            operandStack.push(int(token))
        elif token in prec:
            op2 = operandStack.pop()
            op1 = operandStack.pop()
            res = doMath(token, op1, op2)
            operandStack.push(res)
    return operandStack.pop()
示例#36
0
def evalPostfix(postfixExpr):
    operandStack = Stack()
    tokenList = postfixExpr.split()
    prec = {'*': 3, '/': 3, '+': 2, '-': 2, '(': 1}
    for token in tokenList:
        if token.isdigit():
            operandStack.push(int(token))
        elif token in prec:
            op2 = operandStack.pop()
            op1 = operandStack.pop()
            res = doMath(token, op1, op2)
            operandStack.push(res)
    return operandStack.pop()
def revstring(sg):
    s = Stack()

    lst = [i for i in sg]
    res = []

    for c in lst:
        s.push(c)

    while not s.isEmpty():
        res.append(s.pop())

    return "".join(res)
def base_converter(dec_num, base):
    digits = "0123456789ABCDEF"

    baseStack = Stack()
    str = ""
    while dec_num > 0:
        baseStack.push(dec_num % base)
        dec_num = dec_num // base

    while not baseStack.isEmpty():
        str = str + digits[baseStack.pop()]

    return str
示例#39
0
def decTobinary(dec):
    s = Stack()

    while dec > 0:
        a = dec % 2
        s.push(a)
        dec = dec // 2

    binary = ''
    while not s.isEmpty():
        binary = binary + str(s.pop())

    return binary
def base_converter(dec_num, base):
    s = Stack()
    digits = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    while dec_num > 0:
        rem = dec_num % base
        s.push(rem)
        dec_num = dec_num // base

    conv_str = ''
    while not s.isEmpty():
        conv_str += digits[s.pop()]

    return conv_str
示例#41
0
def postfixValue(postfixExpr):
    operandStack = Stack()
    #tokenList = postfixExpr.split()

    for token in postfixExpr:
        if token in '0123456789':
            operandStack.push(int(token))
        else:
            operand1 = operandStack.pop()
            operand2 = operandStack.pop()
            result = domath(token, operand2, operand1)
            operandStack.push(result)
    return operandStack.pop()
示例#42
0
def postfixEval(postfixexpr):  # also fix this to do floats
    operandStack = Stack()
    tokenList = postfixexpr.split()

    for token in tokenList:
        if isfloat(token):
            operandStack.push(float(token))
        else:
            operand2 = operandStack.pop()
            operand1 = operandStack.pop()
            result = doMath(token,operand1,operand2)
            operandStack.push(result)
    return operandStack.pop()
def anyBaseConversion(number: int,base: int) -> str:
    digits = "0123456789ABCDEF"
    stack = Stack()
    while number > 0:
        remainder = number%base
        stack.push(remainder)
        number = number//base
    
    res = ""
    while not stack.isEmpty():
        res += digits[stack.pop()]

    return res
示例#44
0
def postfixEval(postfixExpr):
    operandStack = Stack()
    tokenList = postfixExpr.split()

    for token in tokenList:
        if token in "0123456789":
            operandStack.push(int(token))
        else:
            operand2 = operandStack.pop()
            operand1 = operandStack.pop()
            result = doMath(token,operand1,operand2)
            operandStack.push(result)
    return operandStack.pop()
示例#45
0
def dividedDecNumBy2(decNumber):
    remaindersStack = Stack()

    while decNumber > 0:
        remainer = decNumber % 2
        remaindersStack.push(remainer)
        decNumber = decNumber // 2

    binaryResult = ""
    while not remaindersStack.isEmpty():
        binaryResult = binaryResult + str(remaindersStack.pop())

    return binaryResult
示例#46
0
def divideBy2(decNumber):
    remstack = Stack()

    while decNumber > 0:
        rem = decNumber % 2
        remstack.push(rem)
        decNumber = decNumber // 2

    binString = ""
    while not remstack.isEmpty():
        binString = binString + str(remstack.pop())

    return binString
示例#47
0
def postfixEval(postfixExpr):
    operandStack = Stack()
    tokenList = postfixExpr.split()

    for token in tokenList:
        if token in "0123456789":
            operandStack.push(int(token))
        else:
            operand2 = operandStack.pop()
            operand1 = operandStack.pop()
            result = doMath(token, operand1, operand2)
            operandStack.push(result)
    return operandStack.pop()
示例#48
0
def balance_parens(infix_string):
	valid_ops = ["+", "-", "*", "/"]
	opstack = Stack()
	output = list()
	infix_string = infix_string.split()
	for char in infix_string:
		if char == "(":
			opstack.push(char)
		elif char == ")":
			opstack.pop()
		elif char in valid_ops:
			opstack.append(char)
	return output
def toStr(num, base):
    lst = Stack()
    convertString = "0123456789ABCDEF"
    rst = []
    while num > 0:
        if num < base:
            lst.push(convertString[num])
        else:
            lst.push(convertString[num % base])
        num = num // base
    while not lst.isEmpty():
        rst.append(lst.pop())
    return ''.join(rst)
def divide2(desNumber):
    s = Stack()

    while desNumber > 0:
        rem = desNumber % 2
        s.push(rem)
        desNumber = desNumber // 2

    binString = ""
    while not s.isEmpty():
        binString = binString + str(s.pop())

    return binString
def divideBy2(decNumber):
    remstack = Stack()

    while decNumber > 0:
        rem = decNumber % 2
        remstack.push(rem)
        decNumber = decNumber // 2

    binString = ""
    while not remstack.isEmpty():
        binString = binString + str(remstack.pop())

    return binString
示例#52
0
def divide2(desNumber):
    s = Stack()
    while desNumber > 0:
        rem = desNumber % 2  #取余数

        s.push(rem)  #push()将一个新项放到栈的顶部
        desNumber = desNumber // 2  #  取整

    binString = ""
    while not s.isEmpty():  #isEmpty()测试是否为空
        binString = binString + str(s.pop())  #pop()从栈中删除顶部项

    return binString
示例#53
0
def six(desnumber2, base):
    a = '0123456789ABCDEF'
    s = Stack()
    while desnumber2 > 0:
        h = desnumber2 % base
        s.push(h)
        desnumber2 = desnumber2 // base

    bin = ""
    while not s.isEmpty():
        bin = bin + a[s.pop()]

        return bin
示例#54
0
def divide3(desNumber1, base):
    a = "0123456789ABCDEF"
    s = Stack()

    while desNumber1 > 0:
        b = desNumber1 % 2
        s.push(b)
        desNumber1 = desNumber1 // base
    c = ""
    while not s.isEmpty():
        c = c + a[s.pop()]

    return c
示例#55
0
def BaseConversion(origin_number, random_base, random_weight):
    digits = "0123456789ABCDEF"
    target_number = ""
    S = Stack()

    if origin_number < 0:
        neg_flag = True
        if random_base in [10, 16]:
            origin_number = -origin_number
        else:
            origin_number = -(origin_number + 1)
    else:
        neg_flag = False

    while True:
        number = origin_number // random_base
        rem = origin_number % random_base
        bit = str(digits[int(rem)])
        S.push(bit)
        # print(bit)
        if number == 0:
            break
        origin_number = number

    while not S.isEmpty():
        target_bit = S.pop()

        if neg_flag == True and random_base == 2:
            if target_bit == "0":
                target_bit == "1"
            else:
                target_bit == "0"

        target_number = target_number + target_bit

    while True:
        if len(target_number) < random_weight and random_base == 2:
            if neg_flag == True:
                target_number = "1" + target_number
            else:
                target_number = "0" + target_number
        else:
            break

    if random_base in [10, 16]:
        if neg_flag == True:
            target_number = "-" + target_number
        else:
            target_number = " " + target_number

    return target_number
def baseConverter(decNumber, base):
    digits = string.digits + string.uppercase
    s = Stack()

    while decNumber > 0:
        rem = decNumber % base
        s.push(rem)
        decNumber /= base

    res = []
    while not s.isEmpty():
        res.append(str(digits[s.pop()]))

    return "".join(res)
def divideBase(desNumber, base):  # base为进制解释
    digits = '0123456789ABCDEF'  #十六进制
    s = Stack()

    while desNumber > 0:
        rem = desNumber % base
        s.push(rem)
        desNumber = desNumber // base

    binString = ""
    while not s.isEmpty():
        binString = binString + digits[s.pop()]

    return binString
def postfix_eval(p):
    opdstack = Stack()
    token_list = p.split()

    for token in token_list:
        if token in '0123456789':
            opdstack.push(int(token))
        else:
            opd1 = opdstack.pop()
            opd2 = opdstack.pop()
            result = do_math(token, opd1, opd2)
            opdstack.push(result)

    return opdstack.pop()
示例#59
0
def dividedBy2(decNumber):
    remstack = Stack()
    while decNumber > 0:
        rem = decNumber % 2
        remstack.push(rem)
        decNumber = decNumber // 2

    binString = ''
    # binString=0
    while not remstack.isEmpty():
        binString = binString + str(remstack.pop())  #字符串组合延长
        # binString=binString*10+remstack.pop()

    return binString
示例#60
0
def baseConverter(decNumber, base):
    digits = '0123456789ABCDEF'
    remStack = Stack()

    while decNumber > 0:
        rem = decNumber % base
        remStack.push(rem)
        decNumber = decNumber // base

    newString = ''
    while not remStack.isEmpty():
        newString = newString + digits[remStack.pop()]

    return newString