Python Forum
Reduce file size - simplify code
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Reduce file size - simplify code
#1
Hello everyone,
I'm learning a python right now and just experimented a bit by writing a small program.
My problem is that the outcomming file size is pretty huge. It's ~150MB which I dont think is an appropriate size for a program of this kind. It's just a simple calculator for plotting circles.
Can someone give me a hint how to minimize the size? Maybe code or compiling changes will do it, but I'm not sure how to do it since I'm a beginner.
I know the code ist "complicated" and can be simplified for sure. But I wanted to keep it easy and didn't want to implement functions I've not learned yet.
Some advice for some cosmetic changes to reduce file and code size would be great!
greetings

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
import tkinter
from tkinter import *
from tkinter import messagebox
import math
from mpmath import *
from sympy import *
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
matplotlib.use("TkAgg")
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk)
 
    ###Berechnung der Werte bei gegebenem/gegebener Kreisbogen/Kreissehne
    ###bzw. Kreissektor/Kreissehne mit der Newton Methode
 
def newton(f,Df,x0,epsilon,max_iter):
   xn = x0
   for n in range(0,max_iter):
        fxn = f(xn)
        if abs(fxn) < epsilon:
            return xn
        Dfxn = Df(xn)
        if Dfxn == 0:
            return -1
        xn = xn - fxn/Dfxn
   return -1
    
def deploy(f,x0,epsilon,max_iter,acc):
     xn = x0
     for n in range(0,max_iter):
            fxn = f(xn)
            if abs(fxn) < epsilon:
                return xn
            xn = xn + (acc)
     return -1
 
###Funktion für neue Eingabe
 
def delete_entry_fields():
 e1.delete(0,END)
 e2.delete(0,END)
 e3.delete(0,END)
 e4.delete(0,END)
 e5.delete(0,END)
 e1.insert(10,"0")
 e2.insert(10,"0")
 e3.insert(10,"0")
 e4.insert(10,"0")
 e5.insert(10,"0")
 
###Berechnungen der Werte
 
def calc():
 n1 = float(e1.get())
 n2 = float(e2.get())
 n3 = float(e3.get())
 n4 = float(e4.get())
 n5 = float(e5.get())
 if n1 > 0 and n2 > 0 and n3 == 0 and n4 == 0 and n5 == 0 and n2 <= 360:
   e3.delete(0,END)
   e4.delete(0,END)
   e5.delete(0,END)
   r1 = n1 * math.pi * n2 / 180
   e3.insert(10,round(r1,3))
   r2 = n1 * 2 * math.sin(n2*math.pi/180/2)
   e4.insert(10,round(r2,3))
   r3 = n1 ** 2 * math.pi * n2/360
   e5.insert(10,round(r3,3))
 elif n2 > 0 and n3 > 0 and n1 == 0 and n4 == 0 and n5 == 0 and n2 <= 360:
   e1.delete(0,END)
   e4.delete(0,END)
   e5.delete(0,END)
   r1 = n3 / (n2 / 180 * math.pi)
   e1.insert(10,round(r1,3))
   r2 = r1 * 2 * math.sin(n2*math.pi/180/2)
   e4.insert(10,round(r2,3))
   r3 = r1 ** 2 * math.pi * n2/360
   e5.insert(10,round(r3,3))
 elif n3 > 0 and n4 > 0 and n3 > n4 and n1 == 0 and n2 == 0 and n5 == 0:
   e1.delete(0,END)                 
   e2.delete(0,END)                     
   e5.delete(0,END)
   m1 = n3
   m2 = n4
   f = lambda x: 2*x*math.sin((m1/2)/x)-m2
   Df = lambda x: 2*math.sin((m1/2)/x)-((n1*math.cos((m1/2)/x))/(x))
   approxi = newton(f,Df,4,1e-3,100)
   e1.insert(10,round(abs(approxi),3))
   r1 = n3 / approxi * 57.2958
   e2.insert(10,round(abs(r1),3))
   r3 = approxi ** 2 * math.pi * r1/360
   e5.insert(10,round(abs(r3),3))
 elif n4 > 0 and n5 > 0 and n1 == 0 and n2 == 0 and n3 == 0:
   e1.delete(0,END)                 
   e2.delete(0,END)                     
   e3.delete(0,END)
   f = lambda x: (n4/math.sin(x/2)/2)**2*math.pi*x/(2*math.pi)-n5
   if n4 < 1 and n5 < 1:
    approxi = deploy(f,0.001,0.01,90000,0.0001)
   if n4 > n5 and n4 <= 2.546:
    approxi = deploy(f,0.0001,0.0001,900000,0.0001)
   if n4 >= 1 and n4 >= 1 and n4 < 60 and n5 < 100:
    approxi = deploy(f,0.0001,1,90000,0.001)
   if n4 >= 60 or n5 >= 100:
    approxi = deploy(f,0.0001,100,90000,0.001)
   if approxi == -1:
    messagebox.showerror("Ungültige Eingabe", "Für die gegebenen Werte ist keine Berechnung möglich.")
   r1 = approxi * 180 / math.pi
   e2.insert(10,round(r1,3))
   r2 = n4 / (2*sin(r1*math.pi/180/2))
   e1.insert(10,round(r2,3))
   r3 = r2 * 2 * math.pi * r1/360
   e3.insert(10,round(r3,3))
 elif n3 > 0 and n5 > 0 and n1 == 0 and n2 == 0 and n4 == 0 and n2 <= 360:
   e1.delete(0,END)
   e2.delete(0,END)
   e4.delete(0,END)
   r1 = 360 * (n3 ** 2) / (4 * math.pi * n5)
   e2.insert(10,round(r1,3))
   r2 = 360 * n3 / (2 * math.pi * r1)
   e1.insert(10,round(r2,3))
   r3 = r2 * 2 * math.sin(r1*math.pi/180/2)
   e4.insert(10,round(r3,3))
 elif n1 > 0 and n3 > 0 and n2 == 0 and n4 == 0 and n5 == 0 and 2 * n1 * math.pi >= n3:
   e2.delete(0,END)
   e4.delete(0,END)
   e5.delete(0,END)
   r1 = n3 / n1 * (180 / math.pi)
   e2.insert(10,round(r1,3))
   r2 = n1 * 2 * math.sin(r1*math.pi/180/2)
   e4.insert(10,round(r2,3))
   r3 = n1 ** 2 * math.pi * r1/360
   e5.insert(10,round(r3,3))
 elif n1 > 0 and n4 > 0 and n2 == 0 and n3 == 0 and n5 == 0 and n1 * 2 >= n4:
   e2.delete(0,END)
   e3.delete(0,END)
   e5.delete(0,END)
   a = (2 * n1 - math.sqrt(4 * (n1 ** 2) - (n4 ** 2))) / 2
   r1 = 2 * math.asin(n4 / (2 * n1)) * (180 / math.pi)
   e2.insert(10,round(r1,3))
   r2 = n1 * math.pi * r1 / 180
   e3.insert(10,round(r2,3))
   r3 = n1 ** 2 * math.pi * r1/360
   e5.insert(10,round(r3,3))
 elif n1 > 0 and n5 > 0 and n2 == 0 and n3 == 0 and n4 == 0 and math.pi * n1 ** 2 >= n5:
   e2.delete(0,END)
   e3.delete(0,END)
   e4.delete(0,END)
   r1 = n5 / (n1 ** 2) / math.pi * 360
   e2.insert(10,round(r1,3))
   r2 = 2 * n1 * math.pi * r1 / 360
   e3.insert(10,round(r2,3))
   r3 = n1 * 2 * math.sin(r1*math.pi/180/2)
   e4.insert(10,round(r3,3))
 elif n2 > 0 and n4 > 0 and n1 == 0 and n3 == 0 and n5 == 0 and n2 <= 360:
   e1.delete(0,END)
   e3.delete(0,END)
   e5.delete(0,END)
   r1 = n4 / (2*sin(n2*math.pi/180/2))
   e1.insert(10,round(r1,3))
   r2 = r1 * math.pi * n2 / 180
   e3.insert(10,round(r2,3))
   r3 = r1 ** 2 * math.pi * n2/360
   e5.insert(10,round(r3,3))
 elif n2 > 0 and n5 > 0 and n1 == 0 and n3 == 0 and n4 == 0 and n2 <= 360:
   e1.delete(0,END)
   e3.delete(0,END)
   e4.delete(0,END)
   r1 = math.sqrt(n5 / math.pi / n2 * 360)
   e1.insert(10,round(r1,3))
   r2 = r1 * math.pi * n2 / 180
   e3.insert(10,round(r2,3))
   r3 = r1 * 2 * math.sin(n2*math.pi/180/2)
   e4.insert(10,round(r3,3))
 elif n4 > n5 and n4 > 2.546:
    messagebox.showerror("Ungültige Eingabe", "Die Kreissektorfläche kann die Sekantenlänge nicht derart unterschreiten.")
 elif n1 * 2 < n4:
    messagebox.showerror("Ungültige Eingabe", "Die Kreissehne überschreitet den Kreisdurchmesser.")
 elif n1 ** 2 * math.pi < n5:
    messagebox.showerror("Ungültige Eingabe", "Der Flächeninhalt des Kreisauschnitts überschreitet den des gesamten Kreises.")
 elif n1 > 0 and n3 > 0 and n2 == 0 and n4 == 0 and n5 == 0 and 2 * n1 * math.pi < n3:
    messagebox.showerror("Ungültige Eingabe", "Das angegebene Bogenmaß überschreitet den Kreisumfang.")
 elif n2 > 0 and n5 > 0 and n1 == 0 and n3 == 0 and n4 == 0 and n2 > 360:
    messagebox.showerror("Ungültige Eingabe", "Der maximale Sektorwinkel kann 360° nicht überschreiten.")
 elif n2 > 0 and n4 > 0 and n1 == 0 and n3 == 0 and n5 == 0 and n2 > 360:
    messagebox.showerror("Ungültige Eingabe", "Der maximale Sektorwinkel kann 360° nicht überschreiten.")
 elif n2 > 0 and n3 > 0 and n1 == 0 and n4 == 0 and n5 == 0 and n2 > 360:
    messagebox.showerror("Ungültige Eingabe", "Der maximale Sektorwinkel kann 360° nicht überschreiten.")
 elif n1 > 0 and n2 > 0 and n3 == 0 and n4 == 0 and n5 == 0 and n2 > 360:
    messagebox.showerror("Ungültige Eingabe", "Der maximale Sektorwinkel kann 360° nicht überschreiten.")
 elif n1 > 0 and n2 > 0 and n3 > 0 and n4 > 0 and n5 > 0 or\
    n1 > 0 and n2 > 0 and n3 > 0 and n4 > 0 or\
    n1 > 0 and n2 > 0 and n3 > 0 and n5 > 0 or\
    n1 > 0 and n2 > 0 and n4 > 0 and n5 > 0 or\
    n1 > 0 and n3 > 0 and n4 > 0 and n5 > 0 or\
    n1 > 0 and n2 > 0 and n3 > 0 or\
    n1 > 0 and n2 > 0 and n4 > 0 or\
    n1 > 0 and n2 > 0 and n4 > 0 or\
    n1 > 0 and n2 > 0 and n5 > 0 or\
    n1 > 0 and n3 > 0 and n4 > 0 or\
    n1 > 0 and n3 > 0 and n5 > 0 or\
    n2 > 0 and n3 > 0 and n4 > 0 or\
    n3 > 0 and n4 > 0 and n5 > 0 or\
    n2 > 0 and n4 > 0 and n5 > 0 or\
    n2 > 0 and n3 > 0 and n5 > 0 or\
    n1 > 0 and n4 > 0 and n5 > 0 or\
    n1 == 0 and n2 == 0 and n3 == 0 and n4 == 0 and n5 == 0 or\
    n1 == 0 and n2 == 0 and n3 == 0 and n4 == 0 or\
    n1 == 0 and n2 == 0 and n3 == 0 and n5 == 0 or\
    n1 == 0 and n2 == 0 and n5 == 0 and n4 == 0 or\
    n1 == 0 and n5 == 0 and n3 == 0 and n4 == 0 or\
    n5 == 0 and n2 == 0 and n3 == 0 and n4 == 0:
     messagebox.showerror("Ungültige Eingabe", "Bitte exakt zwei Eingaben tätigen.")
 else:
    messagebox.showerror("Ungültige Eingabe", "Achten Sie auf die in der Beschreibung angegebene Syntax.")
 
 
    ###Darstellung der Grafik
      
 rest = math.pi*(float(e1.get())**2)
 
 labels = 'Kuchenstück', 'Rest'
 sizes = [float(e5.get()), rest-float(e5.get())]
     
 explode = (0.1, 0)
 
 fig, ax1 = plt.subplots()
 ax1.pie(sizes, explode=explode, labels=labels, shadow=True, startangle=90)
 ax1.axis('equal')
 canvas1 = FigureCanvasTkAgg(fig, master=root)  # A tk.DrawingArea.
 canvas1.draw()
 canvas1.get_tk_widget().grid(columnspan=10, rowspan=10, row=0, column=7, ipadx=0, pady=30)
 canvas1.pack
 
  
 
    ###HauptfensterGUI
 
 
root = tkinter.Tk()
display1 = Canvas()
display1.config(width=1300, height=600)
display1.grid(row=0, rowspan=300, columnspan=100)
display1.create_rectangle(0, 0, 3000, 3000, fill="azure")
display3 = Canvas()
display3.config(width=700, height=600)
display3.grid(row=0, column=6, rowspan=13, columnspan=12)
display3.create_rectangle(0, 0, 2000, 2000, fill="steel blue")
display2 = Canvas()
display2.config(width=650, height=500)
display2.grid(row=0, column=7, rowspan=10, columnspan=10, ipadx=0)
display2.create_rectangle(0, 0, 2000, 2000, fill="white")
root.title("Kuchenstück-Rechner 2019")
root.geometry("1240x566")
root.iconbitmap('cake1.ico')
root.resizable(width=False, height=False)
img = PhotoImage(file='cakebg.png')
panel = Label(root, bg="azure", image = img)
panel.grid(row=2, column=1, rowspan=9, columnspan=4)
 
    ###Labels
 
Label(root, text="Radius", bg="azure").grid(row=0, pady=3)
Label(root, text="Bogenwinkel", bg="azure").grid(row=1, pady=3)
Label(root, text="Bogenlänge", bg="azure").grid(row=2, pady=3)
Label(root, text="Sekantenlänge", bg="azure").grid(row=3, pady=3)
Label(root, text="Flächeninhalt", bg="azure").grid(row=4, pady=3)
Label(root, text="Bitte geben Sie zwei der fünf Werte an, um die übrigen zu berechnen.\n Achten Sie dabei auf die folgende Syntax: ZAHL.NACHKOMMASTELLE.\n Die Werte werden auf die dritte Nachkommastelle gerundet.", bg="steel blue").grid(row=9, column=0, columnspan=3, padx=20, pady=20, ipady=20, ipadx=20)
 
    ###Entries
 
e1 = Entry(root, width=9)
e2 = Entry(root, width=9)
e3 = Entry(root, width=9)
e4 = Entry(root, width=9)
e5 = Entry(root, width=9)
e1.insert(10,"0")
e2.insert(10,"0")
e3.insert(10,"0")
e4.insert(10,"0")
e5.insert(10,"0")
e1.grid(row=0, column=1)
e2.grid(row=1, column=1)
e3.grid(row=2, column=1)
e4.grid(row=3, column=1)
e5.grid(row=4, column=1)
 
    ###Buttons
 
b1 = Button(root, text='Beenden', bg="azure2", command=root.quit).grid(row=7, column=0, columnspan=2, ipadx=56)
b2 = Button(root, text='Berechnen', bg="azure2", command=calc).grid(row=5, column=0, columnspan=2, ipadx=50)
b3 = Button(root, text='Neue Eingabe', bg="azure2", command=delete_entry_fields).grid(row=6, column=0, columnspan=2, ipadx=38)
 
 
root.mainloop()
Reply
#2
The first thing I see is this function:

1
2
3
4
5
6
7
8
9
10
11
def delete_entry_fields():
 e1.delete(0,END)
 e2.delete(0,END)
 e3.delete(0,END)
 e4.delete(0,END)
 e5.delete(0,END)
 e1.insert(10,"0")
 e2.insert(10,"0")
 e3.insert(10,"0")
 e4.insert(10,"0")
 e5.insert(10,"0")
Put all of the entry fields into one list. Then you can do this with a loop:

1
2
3
for entry_field in entry_fields:
    entry_field.delete(0, END)
    entry_field.insret(10, "0")
This has applications throughout your code. If you are numbering things x1 to x5, you should just put them all in a list.

In the calc function, you have lots of conditionals like this:

1
if n1 > 0 and n2 > 0 and n3 == 0 and n4 == 0 and n5 == 0 and n2 <= 360:
Again, n1 to n5 should be in a list. You should use that list to generalize that conditional. Just have one of them, which picks which items are to be processed in which way, and then after the conditional do the processing.

The conditional on line 192 is insane. It looks like you are trying to check that at least three of n1-n5 are greater than 0 or at least four are equal to 0. Again, the ns should be in a list, let's call it all_ns:

1
2
3
4
over_zero = len([n for n in all_ns if n > 0])
zero = len([n for n in all_ns if n == 0])
if over_zero >= 3 or zero >= 4:
    ...
That should replace the entire conditional starting on line 192.

All that said, this is a GUI and you are not using object oriented programming (OOP). You really should learn OOP and how classes work. You can start with the classes tutorial link in my signature below.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
Thank you for your quick answer!

I took your advice and reworked the code. It looks a little bit better by now.
I'm learning OOP right now, so I didn't want to use mechanics I'm not familiar with.
Just wanted to experiment with some functions to get a little peak on what is possible to create, I'm not planning to do sloppy work or learn overhasty.
I know that learning a language takes a lot time, and I'm willing to learn it step by step, so I will check out your OOP guide for sure!

Like I said thank you very much for your hints Smile
Reply
#4
just to add a couple points you can use just one canvas and create many rectangles.
in here
1
2
3
4
5
6
7
8
9
10
11
12
13
root = tkinter.Tk()
display1 = Canvas()
display1.config(width=1300, height=600)
display1.grid(row=0, rowspan=300, columnspan=100)
display1.create_rectangle(0, 0, 3000, 3000, fill="azure")
display3 = Canvas()
display3.config(width=700, height=600)
display3.grid(row=0, column=6, rowspan=13, columnspan=12)
display3.create_rectangle(0, 0, 2000, 2000, fill="steel blue")
display2 = Canvas()
display2.config(width=650, height=500)
display2.grid(row=0, column=7, rowspan=10, columnspan=10, ipadx=0)
display2.create_rectangle(0, 0, 2000, 2000, fill="white")
when you clear the entries I added a clear the canvas: you won't need the global after
you create a class.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
def delete_entry_fields():
 global canvas1
 e1.delete(0,END)
 e2.delete(0,END)
 e3.delete(0,END)
 e4.delete(0,END)
 e5.delete(0,END)
 e1.insert(10,"0")
 e2.insert(10,"0")
 e3.insert(10,"0")
 e4.insert(10,"0")
 e5.insert(10,"0")
 canvas1._tkcanvas.delete('all')
global canvas1
fig, ax1 = plt.subplots()
ax1.pie(sizes, explode=explode, labels=labels, shadow=True, startangle=90)
ax1.axis('equal')
canvas1 = FigureCanvasTkAgg(fig, master=root)  # A tk.DrawingArea.
canvas1.draw()
canvas1.get_tk_widget().grid(columnspan=10, rowspan=10, row=0, column=7, ipadx=0,pady=30)
  
finally try and steer the user to just 2 options maybe use radio or checkboxes to only allow 2 active entries that's got to make your if statements a lot easier. I'm not a fan of the single space indent, imo. Best of luck
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Reduce PDF Size bg3075 0 2,763 Apr-16-2024, 05:21 PM
Last Post: bg3075

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020