I'm trying to figure out a good way to loop over function arguments. I have the code below, and I just brute forced it for three different cases, "3 point", "5 point", and "7 point". Each of these cases have corresponding variables such as "P_list_3point", "xpoints_3point", etc.
I know one way to simplify the code below is to create a function out of each "block" of code since they repeat the same process, but how would I then loop over the arguments? like each case (3 point, 5pt, 7pt) has a series of corresponding vectors, how do i automate inputting these vectors into the actual function? i'm only working with three cases, but what would be a good way to structure it if i was working with 1000? apologies for any nooby mistakes i'm still pretty bad at coding
T1 = 298 #incoming temperature, dummy value in K
P1 = 10 #incoming pressure, dummy value in atmospheres
M1 = 1.4349 #inlet mach number
gamma = 1.4
P_list_3point = np.zeros(len(xpoints_3point))
T_list_3point = np.zeros(len(xpoints_3point))
M_list_3point = ypoints_3point
for i in range(len(xpoints_3point)):
P_list_3point[i] = SolveP(P1, M_list_3point[i], gamma)
T_list_3point[i] = SolveT(T1, M_list_3point[i], gamma)
P_list_5point = np.zeros(len(xpoints_5point))
T_list_5point = np.zeros(len(xpoints_5point))
M_list_5point = ypoints_5point
for i in range(len(xpoints_5point)):
P_list_5point[i] = SolveP(P1, M_list_5point[i], gamma)
T_list_5point[i] = SolveT(T1, M_list_5point[i], gamma)
P_list_7point = np.zeros(len(xpoints_7point))
T_list_7point = np.zeros(len(xpoints_7point))
M_list_7point = ypoints_7point
for i in range(len(xpoints_7point)):
P_list_7point[i] = SolveP(P1, M_list_7point[i], gamma)
T_list_7point[i] = SolveT(T1, M_list_7point[i], gamma)
CodePudding user response:
Here's a simple way, if I understand your question correctly. I am assuming xpoint_n_points, ypoints_npoint
are given.
def xPoints(xpoint_n_points, ypoints_npoint):
length = len(xpoint_n_points)
P_list_npoint = np.zeros(length)
T_list_npoint = np.zeros(length)
M_list_npoint = ypoints_npoint
for i in range(length):
P_list_npoint[i] = SolveP(P1, M_list_npoint[i], gamma)
T_list_npoint[i] = SolveT(T1, M_list_npoint[i], gamma)
return [P_list_npoint, T_list_npoint]
CodePudding user response:
You can use a dictionary to represent each point variables:
# Create a dictionary to represent the lists
P_list = {}
T_list = {}
M_list = {}
def ProcessPoint(point):
# Assuming xpoints, ypoints are also dictionary or you can convert it into dictionary
P_list[point] = np.zeros(len(xpoints[point]))
T_list[point] = np.zeros(len(xpoints[point]))
M_list[point] = ypoints[point]
for i in range(len(xpoints[point])):
P_list[point][i] = SolveP(P1, M_list[point][i], gamma)
T_list[point][i] = SolveT(T1, M_list[point][i], gamma)
# Then you can call the function for each points
ProcessPoint(3)
ProcessPoint(5)
ProcessPoint(7)