在课堂上,我们刚刚开始学习位串闪烁,从基本函数开始:LSHIFT、RSHIFT、LCIRC、RCIRC、AND、XOR、OR。然后,突然间,我们被赋予了编写一个 Python 程序来解析和评估位串表达式的任务。虽然我发现手动解决位串表达式相当简单,但我没有很好地掌握通过 python 解析和评估位串表达式的有效方法。我在下面定义了所有必需的函数,它们适用于单运算符表达式(即 LCIRC 4 0010),但到目前为止,我完全不知道如何解析多运算符表达式(即 LCIRC 3 LCIRC 3 0010)。
import collections
commands = ["LCIRC","RCIRC"]
i = 0
parse = input("Enter a string here to be evaluated. Use bitstrings only, as this program cannot catch any exceptions otherwise. -->").upper().replace("AND","&").replace("OR","|").replace("XOR","^").replace("NOT","~").split(" ")
#parsing the function
def lcirc(circ,operand):
circ = int(parse[i+1])
operand = list(parse[i-1])
parse.pop(i);parse.pop(i);parse.pop(i);
length = len(operand)
circ = circ % length
operand = operand[circ % length:]+ operand[:circ % length]
operand = "".join(operand)
return operand
def rcirc(Rcirc,operand):
Rcirc = int(parse[i+1])
operand = list(parse[i-1])
parse.pop(i);parse.pop(i);parse.pop(i);
length = len(operand)
Rcirc = Rcirc % length
operand = operand[-Rcirc % length:]+ operand[:-Rcirc % length]
operand = "".join(operand)
return operand
def rshift(shift,operand):
shift = parse[i+1]
operand = list(parse[i+2])
parse.pop(i);parse.pop(i);parse.pop(i);
print(operand)
length = len(operand)
if int(shift) >= len(operand):
for a in range(0,len(operand)):
operand.insert(0,"0")
if int(shift) < len(operand):
for a in range(0,int(shift)):
operand.insert(0,"0")
operand = operand[:length]
operand = "".join(operand)
return operand
def lshift(shift,operand):
shift = parse[i+1]
operand = list(parse[i+2])
parse.pop(i);parse.pop(i);parse.pop(i);
length = len(operand)
if int(shift) >= len(operand):
for a in range(0,len(operand)):
operand.insert(length,"0")
if int(shift) < len(operand):
for a in range(0,int(shift)):
operand.insert(length,"0")
operand = operand[-length:]
operand = "".join(operand)
return operand
def and(op1, op2): #operand1, operand2
return str(bin(int(op1,2) & int(op2,2))).replace("0b","")
def xor(op1, op2): #operand1, operand2
return str(bin(int(op1,2) ^ int(op2,2))).replace("0b","")
def or(op1, op2): #operand1, operand2
return str(bin(int(op1,2) | int(op2,2))).replace("0b","")
def evaluate():
#parsing and evaluating the expression, insert code here.
i = 0
while True:
if "LCIRC" not in parse and "RCIRC" not in parse and "RSHIFT" not in parse and "LSHIFT" not in parse and "~" not in parse and "|" not in parse and "&" not in parse and "^" not in parse:
break
else:
evaluate()
print("Your answer is --> " +"".join(parse))
该程序应该能够接受以下输入:
>>> LCIRC 1 0010
>>> Your answer is --> 0100
>>> LCIRC 1 LCIRC 1 0010
>>> Your answer is 1000