fork download
  1. # your code goes here
  2. operators = ['-', '+', '*', '/']
  3.  
  4. def whitespace(s, pos):
  5. while s[pos] in [' ', '\n', '\t', '\r']:
  6. pos += 1
  7. return pos
  8.  
  9. def num(s, pos):
  10. buf = []
  11. while pos < len(s) and s[pos].isdigit():
  12. buf.append(s[pos])
  13. pos += 1
  14. return (''.join(buf), pos)
  15.  
  16. def flt(s, pos):
  17. n, pos = num(s, pos)
  18. if s[pos] == '.':
  19. pos += 1
  20. n2, pos = num(s, pos)
  21. return n + '.' + n2, pos
  22. return n, pos
  23.  
  24. def op(s, pos):
  25. if s[pos] in operators:
  26. pos += 1
  27. return pos
  28.  
  29. def parse(string):
  30. pos = whitespace(string, 0)
  31. num1, pos = flt(string, pos)
  32. pos = whitespace(string, pos)
  33. pos = op(string, pos)
  34. pos = whitespace(string, pos)
  35. num2, pos = flt(string, pos)
  36. return [num1, num2]
  37.  
  38. print parse("4.7 + 4.1")[1]
  39. print parse("4.7 - 4.2")[1]
  40. print parse("4.7 * 4.3")[1]
Success #stdin #stdout 0s 9024KB
stdin
Standard input is empty
stdout
4.1
4.2
4.3