题目
编写计算器。编写一个程序允许用户选择两个集合:A和B,及运算操作符。例如,in、not in、&、|、^、<等。解析输入的字符串,按照用户选择的运算操作。
程序中判断不同的操作符来进行不同的运算,但是判断的过程中我们要用到很多
if - else
语句感觉特别麻烦。有一种简单的办法我们可以在一个空字典中用键村操作符,用值来存函数名,这样就不需要经过很多的if - else
语句了。参考了一片博客。(因为自己也想到了,但是不知道该怎么写,就参考了一篇博客)思路来源
def handlein(char1, char2):
if char1 in char2:
print('True')
else:
print('False')
def handlenotin(char1, char2):
if char1 not in char2:
print('True')
def handleintersection(char1, char2):
print(set(char1) & set(char2))
def handleunion(char1, char2):
print(set(char1) | set(char2))
def handleXOR(char1, char2):
print(set(char1) ^ set(char2))
def handlesubset(char1, char2):
if set(char1) < set(char2):
print('True')
else:
print('False')
D = {'in': handlein, 'notin': handlenotin, '&': handleintersection, '|': handleunion, '^': handleXOR, '<': handlesubset}
n = input('请输入你要进行的运算: ')
m = n.split( )
char1 = str(m[0])
char2 = str(m[2])
operational = str(m[1])
D[operational](char1, char2)
注意题目中牵扯到了集合运算这时候我们要用
set()
把字符串转换成集合后在进行运算
请输入你要进行的运算: ab ^ abc
{'c'}
请输入你要进行的运算: ab in abc
True
请输入你要进行的运算: ab in a
False
请输入你要进行的运算: abc | abcd
{'b', 'c', 'd', 'a'}
请输入你要进行的运算: abc < abcd
True
请输入你要进行的运算: abc & def
set()