python一道关于编写计算器的题

题目

编写计算器。编写一个程序允许用户选择两个集合: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()
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值