-
Notifications
You must be signed in to change notification settings - Fork 0
/
c3_base10_to_base2.py
127 lines (106 loc) · 3.16 KB
/
c3_base10_to_base2.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
from pythonds.basic import Stack
import string
# # 10进制转换成任意进制
# def myint(num, base):
# digitals = '0123456789ABCDEF'
# result_inv = Stack()
# while num > 0:
# result_inv.push(num % base)
# num = num // base
# i = 0 # delete
# result = ''
# while not result_inv.isEmpty():
# result = result + digitals[result_inv.pop()]
# i = i + 1 #delete
# print(result)
# return result
#
#
# test = 12345
# myint(test, 2)
# 中序表达式转换成后续表达式
def convertor(exp):
first = {'(': 1, '+': 2, '-': 2, '*': 3, '/': 3}
inputs = exp.upper().split()
output = []
oper = Stack()
i = 0
while i < len(inputs):
if inputs[i] in string.ascii_uppercase:
output.append(inputs[i])
elif inputs[i] in list(first.keys()):
if inputs[i] == '(':
oper.push(inputs[i])
else:
while oper.size() != 0 and first[oper.peek()] >= first[inputs[i]]: # 注意此处应该是大于等于,而不是直接大于
output.append(oper.pop())
oper.push(inputs[i])
elif inputs[i] == ')':
while oper.peek() != '(':
output.append(oper.pop())
oper.pop()
else:
print('input Wrong !')
i = i + 1
while not oper.isEmpty():
output.append(oper.pop())
result = ' '.join(output)
print(' '.join(inputs), ' --> ', result)
return result
# convertor('( A + B ) * C - ( D - E ) * ( F + G )') # test
def convertor1(exp):
first = {'(': 1, '+': 2, '-': 2, '*': 3, '/': 3}
inputs = exp.upper().split()
output = []
oper = Stack()
i = 0
while i < len(inputs):
if inputs[i] in list(first.keys()):
if inputs[i] == '(':
oper.push(inputs[i])
else:
while oper.size() != 0 and first[oper.peek()] >= first[inputs[i]]: # 注意此处应该是大于等于,而不是直接大于
output.append(oper.pop())
oper.push(inputs[i])
elif inputs[i] == ')':
while oper.peek() != '(':
output.append(oper.pop())
oper.pop()
else:
output.append(inputs[i])
i = i + 1
while not oper.isEmpty():
output.append(oper.pop())
result = ' '.join(output)
print(' '.join(inputs), ' --> ', result)
return result
def math4(a, b, op):
if op == '+':
r = a + b
elif op == "-":
r = a - b
elif op == '*':
r = a * b
else:
if b == 0:
raise 'Divided by Zero'
else:
r = a / b
return r
def post_caculator(exp):
operand = Stack()
operator = ['+', '-', '*', '/']
exp_list = exp.split()
for i in exp_list:
if i not in operator:
operand.push(int(i))
else:
op2 = operand.pop()
op1 = operand.pop()
operand.push(math4(op1, op2, i))
result = operand.pop()
print(result)
return result
def caculator(s):
post_caculator(convertor1(s))
caculator('( 11 + 12 ) * 1 - ( 2 - 3 ) * ( 4 + 6 ) ')