fork download
  1. #!/usr/bin/env python2
  2.  
  3. """
  4. grph.py
  5.  
  6. LICENSING: PUBLIC DOMAIN
  7.  
  8. Peace... -George
  9. """
  10.  
  11. #_____________________________________________________________________________
  12. # Imports
  13. #
  14. from math import sin, cos, tan
  15. import os
  16. import sys
  17.  
  18. #_____________________________________________________________________________
  19. # Functions
  20. #
  21. def fprintf(fstream, fmt, *args):
  22. """
  23. Emulate C's fprintf() function.
  24. """
  25. fmt %= args
  26. fstream.write(fmt)
  27. return len(fmt)
  28.  
  29. def plot(x_expression, xmin, xmax, ymin, ymax):
  30. """
  31. plot(str, int, int, int, int) -> str
  32.  
  33. Return a string representation of a graph of x_expression.
  34.  
  35. BUGS:
  36. - The graph is inverted.
  37. - Zero Divison Error when expressions like `1/x` are passed as
  38. x_expression.
  39. """
  40. return '\n'.join(
  41. ''.join((
  42. lambda x,y: 'o' if round(eval(x_expression)) == y else (
  43. ' ' if y != 0 and x != 0 else (
  44. '|' if y != 0 and x == 0 else (
  45. '-' if y == 0 and x != 0 else
  46. '+' ))))
  47. (x,y)
  48. for x in xrange(xmax, xmin-1, -1))
  49. for y in xrange(ymax, ymin-1, -1))
  50.  
  51. #_____________________________________________________________________________
  52. # Main function
  53. #
  54. def main():
  55. x_expression = raw_input("f(x) = ")
  56. fprintf(sys.stdout, "\nGraph of f(x) = %s\n%s\n",
  57. x_expression,
  58. plot(x_expression, -10, 10, -10, 10))
  59. return 0
  60.  
  61. if __name__ == '__main__':
  62. main()
  63.  
  64.  
Success #stdin #stdout 0.03s 4720KB
stdin
x + 3
stdout
f(x) = 
Graph of f(x) = x + 3
   o      |          
    o     |          
     o    |          
      o   |          
       o  |          
        o |          
         o|          
          o          
          |o         
          | o        
----------+--o-------
          |   o      
          |    o     
          |     o    
          |      o   
          |       o  
          |        o 
          |         o
          |          
          |          
          |