Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- source2 = "1+2-3*4+3-5/2"
- parsed = []
- source = list(source2)
- parsed2 = []
- def calculate_string(string):
- try:
- for subs in string:
- if subs.isdigit():
- parsed.append(subs)
- if subs == '+':
- parsed.append('+')
- if subs == '-':
- parsed.append('-')
- if subs == '*':
- first = float(string[string.index(subs) - 1])
- second = float(string[string.index(subs) + 1])
- result = first * second
- parsed.append(result)
- parsed.remove(string[string.index(subs) - 1])
- string.remove(string[string.index(subs) + 1])
- if subs == '/':
- first = float(string[string.index(subs) - 1])
- second = float(string[string.index(subs) + 1])
- parsed.append(first / second)
- parsed.remove(string[string.index(subs) - 1])
- string.remove(string[string.index(subs) + 1])
- print "First parsed round = "
- print parsed
- for subs2 in parsed:
- if subs2 == '+':
- first2 = float(parsed[parsed.index(subs2) - 1])
- second2 = float(parsed[parsed.index(subs2) + 1])
- result2 = first2 + second2
- parsed2.append(result2)
- parsed.remove(parsed[parsed.index(subs2) + 1])
- if subs2 == '-':
- first3 = float(parsed[parsed.index(subs2) - 1])
- second3 = float(parsed[parsed.index(subs2) + 1])
- result3 = first3 - second3
- parsed2.append(result3)
- parsed.remove(parsed[parsed.index(subs2) + 1])
- except (ValueError, IndexError):
- print "end"
- return parsed2
- if __name__ == '__main__':
- print calculate_string(source)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement