My problem is that I want:
and then I want it to get evaluted in the calc_energy function 360 times
and then store the result so I could count the year average, I want to calculate the energy average..
Should I call the function instead of return in def_decide(v)???
Could someone help me get in on the right track?
def calc_v(latitud):
for t in range(0,360):
v=(23.5*math.sin(math.pi*(t-80)/180)+90-latitud)/90
decide_v(v):
def decide_v(v):
if 0<v<1:
return(v**2)
if v>=1:
return(1)
if v<=0:
return(0)
def calc_energy(v):
W=self.area*random(0,1)*self.sundigit*v
return W
def sort(self,W):
W+=100/360
You can make a generator from calc_v and then use it as you would use a list of values (notice yield instead of return):
def calc_v(latitude):
for t in range(0,360):
v=(23.5*math.sin(math.pi*(t-80)/180)+90-latitude)/90
yield v
def decide_v(v):
if 0<v<1:
return v**2
elif v>=1:
return 1
else:
return 0
for v in calc_v(latitude):
print decide_v(v)
You can use recursion which is a function calling itself. Below you can see the function factorial is called within itself. http://www.python-course.eu/recursive_functions.php
def factorial(n):
print("factorial has been called with n = " + str(n))
if n == 1:
return 1
else:
res = n * factorial(n-1)
print("intermediate result for ", n, " * factorial(" ,n-1, "): ",res)
return res
I get the feeling that you don't really want to know how to loop a function. I think you just want to call your function in the example that you gave.
def calc_v(latitud):
for t in range(0,366):
v=(23.5*math.sin(math.pi*(t-80)/180)+90-latitud)/90
decide_v(v) # return v
def decide_v(v):
if 0<v<1:
print(v**2)
if v>=1:
print(1)
if v<=0:
print(0)
When you use the return statement in a function then you will leave the loop and the function, so your for loop will only run through t=0 then it will break out of the function. I think you just want to call your function and give it the variable v.
Related
I want to improve the performance of a recursive calculation of values
n = 100
def T(n,k):
q = 0
if n == 0 and k == 0:
return(1)
q = 1
if k>n or n<0:
return(0)
q = 1
if q != 1:
return(T(n-1,k-1)+n*T(n-1,k))
for i in range(n):
for n in range(i+1):
print(T(i,n))
print("*********")
However, I've only found ways to do this with functions that only take 1 argument, like this:
def mem(f):
memory = {}
def inner_function(x):
if x not in memory:
memory[x] = f(x)
return memory[x]
else:
return memory[x]
return inner_function
#mem
def fibonacci(n):
if n == 1 or n == 0:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)
I was thinking of doing a 2d array, but I don't know yet (assuming it's possible) how the idea of doing so, with lists of lists, would help.
You can use functools.lru_cache for this
from functools import lru_cache
#lru_cache(maxsize=32)
def T(n,k):
q = 0
if n == 0 and k == 0:
return(1)
q = 1
if k>n or n<0:
return(0)
q = 1
if q != 1:
return(T(n-1,k-1)+n*T(n-1,k))
You can use this decorator to memoize function calls, with this function in particular this will save up to the maxsize most recent calls.
Note in this particular case, the vast majority of the time is actually spent writing to console because of your print statements. If you remove this (but still leave your T(i,n) invocation) your code will complete almost instantaneously.
You can easily extend your mem decorator to work with variable *args parameters, looking them up in the memory. This would work with **kwargs, too, you'd have to convert them to a hashable type though, e.g. frozenset of tuples. And of course all parameters must be hashable for this.
def mem(f):
memory = {}
def inner_function(*args):
if args not in memory:
memory[args] = f(*args)
return memory[args]
return inner_function
Tested with your T function, works fine. In practice, however, you might still want to use functools.lru_cache.
How to create a functinon in Python such that for example:
n = int(input("number of knots: "))
xsolmed=[]
for i in range(n+1):
xsolmed.append(-1+(2*i/n))
def x(x):
return x
lni=[]
formula=1
for i in range(n+1):
for j in range(n+1):
if i==j:
pass
formula = (x(x)-xsolmed[i])/(xsolmed[j]-xsolmed[i])*formula
I think I need it to return the function such that the formula variable is a function by x in its own right and so later i can call upon it in the fashion
formula(10)=output
Set the results of a function call equal to your desired variable.
def f(x):
"A function that changes nothing"
return x
a = f(5) # same as a = 5
To avoid confusion, I recommend that you don't give functions the same name as their arguments, (i.e., don't do def x(x): ...).
If you want formula to be a function, then declare it as one, after which the correct syntax would be output = formula(10).
formula(10) is instance of a function and hence only has a value not a variable name to assign to.
A good way to write above code will be:
n = int(input("number of knots: "))
xsolmed=[]
for i in range(n+1):
xsolmed.append(-1+(2*i/n))
def y(x):
return x
def formula_calc(X):
formula=1
for i in range(n+1):
for j in range(n+1):
if i==j:
pass
formula = (X-xsolmed[i])/(xsolmed[j]-xsolmed[i])*formula
return formula
# now formula is a function of x. X can itself be a function.
print(formula(y(7))
# this will print value of formula at 7 as x(7) is 7.
How can I put this in recursive? This is an assignment to calculate the factorial of a number and tell if a number is prime or not only using addition and subtraction, but it needs to be in recursive form but I can not figure out how to do it.
def Prod(x,r):
z=0
while x>0:
z=z+r
x=x-1
return z
def Fat(x):
r=1
while x>1:
r=Prod(x,r)
x=x-1
return r
AND
def Divi(x,d):
c=0
while x>=d:
x=x-d
c=c+1
return x
def Pri(x):
r='N'
d=2
while d<x and r=='N':
if(Divi(x,d)==0):
r='S'
d=d+1
if r=='N':
t='its prime'
else:
t='not prime'
return t
Forgot to mention that also I can only use if ... elif ... else nothing but that
A recursive function is just a function that calls itself.
def me():
me()
except, the most trivial recursive function, given above, recurses forever, just like an infinite loop loops forever:
while True:
dab()
So what do you do to prevent the infinite loop? You have a loop condition:
x = 3
while x > 0:
dab()
x -= 1
Now your loop will exit. So how do we prevent a recursive function from looping infinitely? We provide a base case where the recursive function does not call itself:
def dabr(x):
if x <= 0:
return
dabr(x - 1)
In your code above, you exit the loop when x>1 is no longer true. That's your base case. So write that as an if statement, such that the function recurs on itself only when x>1. Here's a hint:
def Fat(x):
if x <= 1:
return ???
return ???
When you are programming recursively, you are calling a function into itself.
def Prod(a, b):
...
def Fat(r=1):
if r <= 1:
return 1
else:
return Prod(r, Fat(r - 1))
In this case, you are calling the function Fat inside itself.
So I'm making a simple program that gets 2 functions(a and k) and one integer value(b), then it gets the formal parameter in the two functions(a and k) which is "x" and applies a condition x < b then based on the condition makes a function call, either a or b. But when I run the program it gives an error that x is not defined in the global frame. I want it to get "x" from the formal parameter assigned to the functions a and b and then get the condition based on that.
Here's my code
def square(x):
return x * x
def increment(x):
return x + 1
def piecewise(a, k, b):
if x<b:
return a
else:
return k
mak = piecewise(increment,square ,3 )
print(mak(1))
I guess you want to do something like this:
def piecewise(a, k, b):
def f(x):
if x < b:
return a(x)
else:
return k(x)
return f
However, I am not sure if it is a good practice. So, I leave my answer here to see the comments and learn if there is any problem with it.
total=0
def f(x):
import math
return 10*math.e**(math.log(0.5)/5.27 * x)
def radio(start,stop,step):
time=stop-start
newstart=start+step
if time !=0:
rad=f(start)*step
global total
total+=rad
radio(newstart,stop,step)
else:
return total
print radio(0, 5, 1)
print radio(5, 11, 1)
print radio(0, 11, 1)
print radio(40, 100, 1.5)
In Python functions return None by default.
You have problem with indentation, therefore your function radio unexpectedly ends and the subsequent code block considered an independent and not belonging to the radio. To solve it - fix the indentation like this:
def radio(start,stop,step):
time=stop-start
newstart=start+step
if time !=0:
rad=f(start)*step
global total
total+=rad
radio(newstart,stop,step)
else:
return total
In python function has to give any return value if no return value are specified then by default None is returned
The first time you called radio function nothing was returned it called itself again due to which None was returned
TO avoid this problem since you are using recursive call you have return value of each function to other function so use return when calling the same function
total=0
def f(x):
import math
return 10*math.e**(math.log(0.5)/5.27 * x)
def radio(start,stop,step):
time=stop-start
newstart=start+step
if time !=0:
rad=f(start)*step
global total
total+=rad
return radio(newstart,stop,step)
else:
return total
print radio(0, 5, 1)
Output:
39.1031878433