Python: Quadriatic Graph Multiple Numbers Error

前端 未结 2 693
野的像风
野的像风 2020-12-12 03:17

I have created a code to print the equation y=x^2+3

However it looks like every time I finish it the y axis has multiple numbers, like top to bottom-19,

相关标签:
2条回答
  • 2020-12-12 03:37

    As you stated, you need to draw the graph "backwards": first print the empty lines between the current y and the previous one, then print the current y value. You need to put the "*" print at the end of the outer loop (the loop on x)

    Next issue is the number of empty lines. Between 19 and 12, you should only have 6 empty lines, because you don't count the line 19 and the line 12.

    old=19
    new=12
    #your code
    old-new+1= 8
    #actual number of empty lines
    old-new-1=6
    

    Next, you have repeated numbers in the y axis because you're always printing the same y. Here:

    for lines in range(0,difference+1):
        print('{0:>3}'.format(str(y)+'|'))
    

    The y stays the same, and is equal to the "new" value. You need to decrease y from "old value -1" to "new value +1". Something like oldY=oldY-1, print(oldY).

    Finally, you never update oldY. At the end of the outer loop, you should have oldY=y

    0 讨论(0)
  • 2020-12-12 03:39

    You could also calculate your values of y in advance and iterate over all y values, inserting markers when a y value matches one of your values to plot, as follows:

    print('{0:>{width}}'.format('y', width=2))
    
    f = lambda x: x**2 + 3
    
    xmax = 4
    xs = range(xmax+1)
    ys = [f(x) for x in xs]
    ymax = max(ys)
    xscale = 5
    i = len(ys)-1
    for y in range(ymax,-1,-1):
        # The y-axis
        print('{0:>3}|'.format(y), end='')
        if i >= 0 and y==ys[i]:
            print('{marker:>{width}}'.format(marker='*', width=xs[i]*xscale))
            i -= 1
        else:
            print()
    print('   L' + '_'*len(xs)*xscale)
    print('    ' + ''.join(['{x:>{xscale}}'.format(x=x, xscale=xscale) for x in xs[1:]]))
    

    Output:

    y
     19|                   *
     18|
     17|
     16|
     15|
     14|
     13|
     12|              *
     11|
     10|
      9|
      8|
      7|         *
      6|
      5|
      4|    *
      3|*
      2|
      1|
      0|
       L_________________________
            1    2    3    4
    
    0 讨论(0)
提交回复
热议问题