r/learnpython • u/Current_Beginning_39 • 10h ago
How to solve python problems?
This may be a dumb questions, but I do not get how to write code. For some context, I am taking a scientific computing course in my uni, I am a physics major, so most of the coding we do pertains to some kinda physics/math related problem. I know how to do the math on its own but I don't get how to translate it into code. When I see a problem I don't even know how to start it.
For example:
Write a function my_cubic_spline_flat(x, y, X), where x and y are arrays containing experimental data points, and X is an array. Assume that x and X are in ascending order and have unique elements. The output argument, Y, should be an array, the same size as X, where Y[i] is the cubic spline interpolation of X[i]. However, instead of the constraints we introduced before, 𝑆′1(𝑥_1)=0 and 𝑆′𝑛−1(𝑥_𝑛)=0.
When I see that, I do not know what to do. Like I know how to write functions and stuff, but not the actual code that goes inside the function.
Any advice is appreciated! :)
3
u/lurgi 10h ago
Do you know what a cubic spline is?
2
u/mc_pm 10h ago
Would you know how to take those lists on paper and work out the spline manually?
1
u/JaguarMammoth6231 10h ago
I assume the course is using the numpy library? Arrays are not a concept built in to python otherwise (though there are lists). You'll need to look at some examples of how to build a numpy array.
1
u/dr_edo_available 9h ago
Start simple. From scratch make a function that adds two numbers.
1
u/tb5841 9h ago
Solving problems is all about breaking them down into tiny steps.
Can you work out the logical steps needed to do this and explain them, one at a time, as if you're describing them to an idiot who has no independent thinking skills.
Once you've done that, you translate each step into code.
1
u/Zeroflops 8h ago
Written from my phone so not clean but.
Take the instructions and turn each line into a comment.
Then for each comment write the code.
For example the first line tells you you need a function. And defines the input and output variables.
Def my_cubic_spline_flat(x:np.array ,y: np.array, X:no.array )-> np.array:
‘’’
x,y = array of points
X= array of values
Y = return array.
‘’’
# Now write out each step as a comment. Then once you have each step to calculate the spline, you fill in the steps with the calculation. Include the checks hinted in the text.
Ex.
# X and Y should be equal lengths.
If len(X) != len(Y):
return 0
return Y
Once done you can remove most of the comments that are not needed.