I'm a beginner, and I have just written this basic code that simply plots a parabola in a graph. Is it possible to make my code more efficient?
The process works by the creating lists of X and Y then adding range of numbers squared to the list Y and normal X to its list and then the function plot simply goes ahead and creates a range doubled + 2 the size ( because the previous range(-size, size)
creates both the minus and positive values and a zero) and fills the canvas.create_line(starting X location, starting Y location, ending X location, ending Y location)
statement and also creates a log.
import tkinter
from tkinter import Tk
# Adding a Tk window
root: Tk = tkinter.Tk()
root.geometry('640x480') # Configuring the resolution
# Adding the canvas to put the graph on it
CanvasNo1 = tkinter.Canvas(root, width=640, height=480)
CanvasNo1.grid()
def draw_axis(canvas_object): # a function in order to draw the horizontal and vertical lines and setting the scroll
canvas_object.update()
x_origin = canvas_object.winfo_width() // 2
y_origin = canvas_object.winfo_height() // 2
canvas_object.configure(scrollregion=(-x_origin, -y_origin, x_origin, y_origin))
canvas_object.create_line(x_origin, 0, -x_origin, 0)
canvas_object.create_line(0, y_origin, 0, -y_origin)
def parabola(number, size): # Calculating the parabola
result = number * number // size
return result
def plot(canvas_object, size, color): # The grand function to do the plotting process
y_location = []
x_location = []
for each in range(-size, size+1):
y_location.append(parabola(each, size))
x_location.append(each)
for each_of in range(0, size*2+2):
if each_of <= size*2-1:
canvas_object.create_line(x_location[each_of], -y_location[each_of], x_location[each_of+1],
-y_location[each_of+1], fill=str(color))
print('A line from X location of {} and Y location of {} to the X location of {} and Y location of {} was'
' drawn, Color = {}'.format(x_location[each_of], y_location[each_of], x_location[each_of+1],
y_location[each_of+1], color))
else:
break
draw_axis(CanvasNo1)
plot(CanvasNo1, 500, 'red')
CanvasNo1.mainloop() # running the window
1 Answer 1
Instead of creating an empty list and appending the values to it, try using list comprehension.
so instead of
y_location = []
x_location = []
for each in range(-size, size+1):
y_location.append(parabola(each, size))
x_location.append(each)
try
y_location = [parabola(each,size) for each in range(-size,size+1)]
x_location = list(range(-size,size+1))
In general you can use a profiler to see which part of your code requires the largest amount of computing making it easier to improve the code. https://docs.python.org/2/library/profile.html
-
\$\begingroup\$ The benefits of list comprehension over a for loop are small. I feel in most cases readability is more valuable than performance gain unless the date you are working with is massive. \$\endgroup\$Mike - SMT– Mike - SMT2019年09月16日 18:11:14 +00:00Commented Sep 16, 2019 at 18:11