python编写一个简单计算器_开发一个简单的python计算器

详解:

1.str.split(分隔符):将str按分隔符进行切片,最后形成的是列表类型

eg:

str = "Line1-abcdef \nLine2-abc \nLine4-abcd";

print str.split( );

print str.split(' ', 1 );

>>['Line1-abcdef', 'Line2-abc', 'Line4-abcd']

>>['Line1-abcdef', '\nLine2-abc \nLine4-abcd']

2.str.join():连接字符串数组。将字符串、元组、列表中的元素以指定的字符(分隔符)连接生成一个新的字符串。

语法: 'sep'.join(seq)

参数说明

sep:分隔符。可以为空

seq:要连接的元素序列、字符串、元组、字典

上面的语法即:以sep作为分隔符,将seq所有的元素合并成一个新的字符串

返回值:返回一个以分隔符sep连接各个元素后生成的字符串

3.sub():按指定的字符进行替换。

Sub(replacement,string[,count =0 ])

1)返回的字符串是在字符串中用RE最左边不重复的匹配来替换。如果模式没有被发现,字符将没有被改变的返回。

2)可选参数count是模式匹配后替换的最大次数;count必须是非负整数。缺省值是0表示替换所有的匹配。

4.grop():获取分段截获的字符串.

需求:

实现加减乘除及拓号优先级解析

用户输入 1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )等类似公式后,必须自己解析里面的(),+,-,*,/符号和公式。

#coding:utf-8

import re

def main():

a = ''.join(raw_input('请输入需要计算的算式').split())

while True:

if '(' in a:

ct = re.search(r'\(([^()]+)\)', a)

if ct is not None:

b = ct.groups()[0]

c = count(b)

a = re.sub(r'\(([^()]+)\)', str(c), a, 1)

else:

c = count(a)

print(c)

break

def add_min(a):

'''

计算加减法

:param:

:return:

'''

if '--' in a:

a = a.replace('--', '+')

c = re.findall(r'-?\d+\.?\d*', a)

ls = []

for i in c:

ls.append(float(i))

rest = sum(ls)

return rest

def mul(a):

'''

计算剩数

:param ct:

:return:

'''

b = re.search(r'\d+\.?\d*(\*-?\d+\.?\d*)+', a)

if b is not None:

b = b.group()

rest = 1

c = re.findall(r'-?\d+\.?\d*', b)

ls =[]

for item in c:

ls.append(float(item))

for i1 in range(len(ls)):

rest = rest * ls[i1]

a = re.sub(r'\d+\.?\d*(\*-?\d+\.?\d*)+', str(rest), a, 1)

return a

def div(a):

'''

计算出发

:param a:

:return:

'''

b = re.search(r'\d+\.?\d*(\/-?\d+\.?\d*)+', a)

if b is not None:

b = b.group()

c = re.findall(r'\d+\.?\d*', b)

#print c

ls =[]

for i in c:

ls.append(float(i))

rest = ls[0]

for i1 in range(1,len(ls)):

rest = rest / ls[i1]

a = re.sub(r'\d+\.?\d*(\/-?\d+\.?\d*)+', str(rest), a, 1)

return a

def count(b):

'''

计算结果

:return:

'''

while True:

if '*' in b:

c = b.split('*')

if '/' in c[0]:

b = div(b)

else:

b = mul(b)

elif '/' in b:

b = div(b)

elif '+' or '-' in b:

b = add_min(b)

return b

else:

return b

main()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值