r/learnpython • u/Current_Beginning_39 • 13h 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! :)
1
u/JaguarMammoth6231 13h 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/Current_Beginning_39 13h ago
yeah we have to use numpy
3
u/JaguarMammoth6231 12h ago
Can you write a function that takes an input array and returns an output array of the same size with each value being the square of the corresponding input value?
If not, can you make a function that returns an array of size 10 with all entries being 0.0 except entry 2 is 7.0?
1
1
u/tb5841 11h 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 11h 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.
3
u/lurgi 13h ago
Do you know what a cubic spline is?