xxxxxxxxxx
HOW TO WRITE BETTER CODE IN PYTHON | TIP #1
1 - List comprehension
#DONT DO THIS:
list = []
for i in range(number):
list.append(i)
#DO THIS:
list = [i for i in range(number)]
xxxxxxxxxx
import numpy as np
from scipy.optimize import minimize
# Define a cubic function to minimize: z = Ax^3 + By + C
def cubic_function(x, A, B, C):
return A * x[0]**3 + B * x[1] + C
# Coefficients for the cubic function
A_coefficient = 2.0
B_coefficient = -3.0
C_constant = 5.0
# Initial guess
initial_guess = [1, 1]
# Minimize the cubic function
result = minimize(cubic_function, initial_guess, args=(A_coefficient, B_coefficient, C_constant), method='Nelder-Mead')
# Print the result
print("Minimum found at x:", result.x)
print("Minimum function value (z):", result.fun)
xxxxxxxxxx
Here is a good optimization trick for many:
#INSTEAD OF:
list = []
for i in range(number):
list.append(value)
#USE:
list = [value for i in range(number]
#INSTEAD OF:
for i in range(len(list)):
#Do something
USE:
for i, value in enumerate(list):
#Do something
APPLYING IT:
#THIS:
matrix = [[0 for i in range(number1)] for j in range(number2)]
#IS BETTER THAN:
matrix = []
for i in range(number1):
row = []
for j in range(number2):
row.append(0)
matrix.append(row)
xxxxxxxxxx
OPTIMIZATION FOR PYTHON: TIP 2 - 4
2 - When importing modules you can import them all in a single line:
import module_1, module_2, module_3, etc
3 - When importing everything from a module use *:
from random import *
We imported everything from the 'random' module using *, now we dont need to use 'random.'
FUN FACT: Not using module. increases performance since module. uses the get_attr function which
decreases performance
4 - When importing only a few things from a module combine the two tips above:
from random import randint, choice
#Now we only import the things we want while also iincreasing performance and start-up time