Jun-09-2020, 09:07 PM
I'm have a problem operating on a set of integers to determine the gradient of the sequence.
in principle it works ok.
I have posted the main code "SourceData" and the function "gradients" to demonstrate the problem by running "SourceData".
Background: in Part B of SourceData I have created an example dataset with a format identical to that which is outside my control as received from a third party.
I have reproduced the same dataset in Part A to show that it can operate correctly, thereby validating the function code.
However, inputting the dataset as the reconstructed variable in Part B fails with the error message
"TypeError: unsupported operand type(s) for +: 'int' and 'str'"
The datasets are identical at the point after they enter the function ( see K1) whether from in both Part A or Part B.
So why the error message in Part B?
Many thanks
Astrikor
in principle it works ok.
I have posted the main code "SourceData" and the function "gradients" to demonstrate the problem by running "SourceData".
Background: in Part B of SourceData I have created an example dataset with a format identical to that which is outside my control as received from a third party.
I have reproduced the same dataset in Part A to show that it can operate correctly, thereby validating the function code.
However, inputting the dataset as the reconstructed variable in Part B fails with the error message
"TypeError: unsupported operand type(s) for +: 'int' and 'str'"
The datasets are identical at the point after they enter the function ( see K1) whether from in both Part A or Part B.
So why the error message in Part B?
Many thanks
Astrikor
#gradients def Trend(newdata): y = newdata print("k1 (in trend function) = ",y) x = range(1,len(y)+1) def var(X): S = 0.0 SS = 0.0 for x in X: S += x SS += x*x xbar = S/float(len(X)) return (SS - len(X) * xbar * xbar) / (len(X) -1.0) def cov(X,Y): n = len(X) xbar = sum(X) / n ybar = sum(Y) / n return sum([(x-xbar)*(y-ybar) for x,y in zip(X,Y)])/(n-1) def beta(x,y): return cov(x,y)/var(x) Gradient = beta(x,y) return Gradient
import gradients print("Part A - direct input to Trend function") k = (2, 4,6,8) Gradient = gradients.Trend(k) print() print("Gradient = ",Gradient) print() print("######################") print() print() print("Part B - indirect input to Trend function") print() print("Create example data list k") x = k = 2 while x < 8: x = x + 2 k = k,x print("k2 = ",k) # remove all brackets from k: k = str(k).replace('(', '').replace(')', '') print("k3 = ",k) k = "({})".format(k) print("k4 formatted to match direct newdata : ",k) print() #send data to Trend function: Gradient = gradients.Trend(k) print() print("Gradient = ",Gradient)