` I am creating a personal graphing system for in terminal use. The class goes as follows:
import parser
def ev(n, x):
code = parser.expr(n).compile()
return eval(code)
class Graph:
def __init__(self, length, width):
self.l = length
self.w = width
self.graph = [['-' for x in range(self.w)] for x in range(self.l)]
def draw(self):
for i in range(self.l):
temp = []
for j in range(self.w):
temp.append(self.graph[i][j])
print ''.join(temp)
def add(self, f):
y = []
for i in range(self.w):
y.append(ev(f, i))
top = max(y)
bot = min(y)
print y
scale = (top - bot)/self.l
print scale
adj = 0
for i in range(self.l,0,1):
adj = bot + (i * scale)
for j in y:
if j >= adj & j < adj + scale:
self.graph[i][j] = 'X'
all runs well except the add module, which creates a range of y values from a pre defined function to parse an equation i.e "x**2" in the last 6 lines of code, it fails, no points in the graph array are modified to 'X'
if anyone would be so kind as to perhaps run and assist, That would be great
There's a few problems:
scale = (top - bot)/self.l
Depending on your version of Python this might do an integer division, so cast to float to make sure you don't round down to zero:
scale = (top - bot)/float(self.l)
Also, subtracting one can avoid an off-by-one error (an array of n items has n-1 steps when iterating from the first to the last element).
scale = (top - bot)/float(self.l-1)
Your range is incorrect (first parameter should be the start value)
for i in range(0,self.l,1):
Lastly, the &
should be an and
(&
is the bitwise and operator)
if j >= adj and j < adj + scale: