Reputation: 11366
I am new to python, so far working more on R. I am trying to learn myself - excuse me if this too basic question.
The following is R program / function that can output nice plot.
# funcomp does some calculations
funcomp <- function(x){
z = x ^2
k= z + x
return(k)
}
#funplot apply funcomp internally and produce plot.
funplot <- function(x){
y <- funcomp(x)
plot(x,y)
}
Applying the function:
funplot(1:10)
I was trying do same in python.
# funcomp does some calculations
def funcomp(x):
z = x ** 2
k= z + x
return k
def funplot(x):
y = funcomp(x)
import matplotlib.pyplot as plt
plt.plot(x, y)
First I just put the above code in the python interpreter.
Applying the function, give me an error.
funcomp(1:10)
funplot(1:10)
I saved the code in the file trial.py
and saved to working directory. And apply the function and got same error.
import trial
trial.funcomp(1:10)
trial.funplot(1:10)
What is problem here and how can I achieve this ?
Edit: I following suggestions below I tried, but does not work well:
trial.fumcomp(range(1,11))
AttributeError: 'module' object has no attribute 'fumcomp'
trial.funplot(range(1,11))
2 def funcomp(x):
----> 3 z = x**2
4 k= z + x
5 return k
TypeError: unsupported operand type(s) for ^: 'list' and 'int'
Upvotes: 1
Views: 53
Reputation: 10841
Instead of:
1:10
... use:
range(1,11)
Further, note that Python does not do vector calculations automatically so you have to explicitly ask Python to do that. I've used a list comprehension for that purpose in funcomp()
(by the way, one problem is that you attempted to call fumcomp()
, which doesn't exist in your code - hence the error message):
# funcomp does some calculations
def funcomp(x):
z = x ** 2
k= z + x
return k
def funplot(x):
y = [funcomp(xx) for xx in x]
import matplotlib.pyplot as plt
plt.plot(x, y)
Given these lines of code:
import trial
import matplotlib.pyplot as plt
trial.funplot(range(1,11))
plt.show()
... the output is:
If you want Python to behave more like R, though, you would be best to use numpy
, e.g. given the code in trial2.py
:
# funcomp does some calculations
def funcomp(x):
z = x ** 2
k= z + x
return k
def funplot(x):
y = funcomp(x)
import matplotlib.pyplot as plt
plt.plot(x, y)
The following code gives the same graph as shown above:
import trial2
import numpy as np
import matplotlib.pyplot as plt
trial2.funplot(np.array(range(1,11)))
plt.show()
... because numpy
arrays are computed as vectors, just as in R.
Upvotes: 1