赞
踩
提取字符串中的最长合法简单数学表达式,字符串长度最长的,并计算表达式的值。如果没有,则返回0。
简单数学表达式只能包含以下内容
0-9数字,符号+-*
1、所有数字,计算结果都不超过long
2、如果有多个长度一样的,请返回第一个表达式的结果
3、数学表达式,必须是合法的,简单的
4、操作符不能连续出现,如+--+1是不合法的
字符串
表达式的值
1-2abcd
-1
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
-
- # 提取字符串中的最长数学表达式并计算
-
- import sys
-
- for line in sys.stdin:
- a = line.split()[0]
- length = len(a)
- ex = ""
- vex = ""
- digits = "0123456789"
- chars = "+-*"
- for i in range(length):
- if a[i] in digits:
- ex = ex + a[i]
- if i != length - 1:
- continue
- elif a[i] in chars:
- if len(ex) == 0:
- continue
- elif ex[-1] in digits:
- ex = ex + a[i]
- if i != length - 1:
- continue
- if len(ex) > 0 and ex[-1] in chars:
- ex = ex[0:-1]
- if len(ex) > len(vex):
- vex = ex
- ex = ""
- if len(vex) > 0:
- print(vex)
- vv = []
- for i in range(len(vex)):
- if vex[i] in digits:
- if len(vv) > 0 and isinstance(vv[-1], int):
- vv[-1] = vv[-1] * 10 + int(vex[i])
- else:
- vv.append(int(vex[i]))
- elif vex[i] in chars:
- vv.append(vex[i])
- vv1 = []
- for j in range(len(vv)):
- if isinstance(vv[j], int):
- if len(vv1) > 0 and vv1[-1] == "*":
- vv1.pop()
- vv1[-1] = vv1[-1] * vv[j]
- else:
- vv1.append(vv[j])
- else:
- vv1.append(vv[j])
- v = 0
- lc = "+"
- for k in range(len(vv1)):
- if isinstance(vv1[k], int):
- if lc == "+":
- v = v + vv1[k]
- elif lc == "-":
- v = v - vv1[k]
- elif isinstance(vv1[k], str):
- lc = vv1[k]
- print(v)
- else:
- print(0)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。