Python: Quadriatic Graph Multiple Numbers Error

前端 未结 2 703
野的像风
野的像风 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: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
    

提交回复
热议问题