Python recursive function recurSum(x, y) - recursion

This is my code:
def recurSum(x, y):
if x <= 1:
return x
return x + recurSum(x - 1)
if y <= 1:
return y
xxwjhefbhwjbfwjh efjehwbf ebrfe
print(recurSum(5, 10))

You can use the following:
def recurSum(x, y):
if x==0:
return y
return recurSum(x - 1, y) + x
In essence, the base case is when the first number has reached 0. If so, you return the other number. Otherwise, you perform once again the recursive sum.

This is another way to do this.
def recurSum(x, y):
return y if x < 1 else recurSum(x-1, x + y)
The expanded form of the above is:
def recurSum(x, runningSum):
if x < 1:
return runningSum;
else:
return recurSum(x-1, x + runningSum)

Does the function need to be recursive? I think you might be over complicating this a bit;
def sums(x,y):
output = y + sum(range(0,x+1))
return output
Here in one line you can add the values between 1 and x to y

Related

Optim Julia parameter meaning

I'm trying to use Optim in Julia to solve a two variable minimization problem, similar to the following
x = [1.0, 2.0, 3.0]
y = 1.0 .+ 2.0 .* x .+ [-0.3, 0.3, -0.1]
function sqerror(betas, X, Y)
err = 0.0
for i in 1:length(X)
pred_i = betas[1] + betas[2] * X[i]
err += (Y[i] - pred_i)^2
end
return err
end
res = optimize(b -> sqerror(b, x, y), [0.0,0.0])
res.minimizer
I do not quite understand what [0.0,0.0] means. By looking at the document http://julianlsolvers.github.io/Optim.jl/v0.9.3/user/minimization/. My understanding is that it is the initial condition. However, if I change that to [0.0,0., 0.0], the algorithm still work despite the fact that I only have two unknowns, and the algorithm gives me three instead of two minimizer. I was wondering if anyone knows what[0.0,0.0] really stands for.
It is initial value. optimize by itself cannot know how many values your sqerror function takes. You specify it by passing this initial value.
For example if you add dimensionality check to sqerror you will get a proper error:
julia> function sqerror(betas::AbstractVector, X::AbstractVector, Y::AbstractVector)
#assert length(betas) == 2
err = 0.0
for i in eachindex(X, Y)
pred_i = betas[1] + betas[2] * X[i]
err += (Y[i] - pred_i)^2
end
return err
end
sqerror (generic function with 2 methods)
julia> optimize(b -> sqerror(b, x, y), [0.0,0.0,0.0])
ERROR: AssertionError: length(betas) == 2
Note that I also changed the loop condition to eachindex(X, Y) to ensure that your function checks if X and Y vectors have aligned indices.
Finally if you want performance and reduce compilation cost (so e.g. assuming you do this optimization many times) it would be better to define your optimized function like this:
objective_factory(x, y) = b -> sqerror(b, x, y)
optimize(objective_factory(x, y), [0.0,0.0])

Could someone explain why this function doesn't always return the first element of the list

I have been having a look at some simple recursive functions to wrap my head around the concept. However one example has me a little confused.
The function below uses recursion to obtain the largest integer from a list:
A = [-4, 2, 4]
n = len(A)
def findMaxRec(A, n):
if (n == 1):
return A[0]
else:
return max(A[n - 1], findMaxRec(A, n - 1))
As n will eventually equal 1 why does the function not always return the first element in the list?
In such cases it might be helpful to just write out what code will be executed. I've tried to do that with your function as pseudo-code, where n is replaced with its value:
findMaxRec(A, 3):
if (3 == 1):
return A[0]
else:
return max(A[3 - 1],
findMaxRec(A, 2):
if (2 == 1):
return A[0]
else:
return max(A[2 - 1],
findMaxRec(A, 1):
if (1 == 1):
return A[0]
)
)
Effectively, this results in:
max(A[2], max(A[1], A[0]))
Where the inner call max(A[1], A[0]) = max(2, -4) = 2
And the outer call max(A[2], ...) = max(4, 2) = 4

How to solve this integral in R?

I need to find evaluate the following function, including an integral, in R:
Probability density functions involving multiple variables, where u = t - y.
The problem I'm running into is that while the input variables of the function as a whole are x and t, the integral needs to be evaluated over the variable u = t - y. The functions f and m' both return values, but I don't know how to make it so that R evaluates the integral over this u rather than x or T.
I currently have the following, but this doesn't return the values I'm supposed to be getting, so I'm wondering if I did it properly?
Thank you in advance!
a = 3
b = 10
T = 2.6
mprime = function(x){
return (1/x)
}
f = function(x){
if (a <= x & x <= b){
return (1/(b-a))
}
else{
return (0)
}
}
toIntegrate = function(u){
return (f(u + x)*mprime(T-u))
}
solution = function (x, T){
return (f(T + x)) + (integrate(toIntegrate(T-y), 0, T))
}
solution(5,T)
There are a few errors in your code:
f and other functions you'll be using in your integration need to be vectorised, i.e. it should take a vector as an input and return a vector as an output.
toIntegrate uses x which is neither a global variable nor an argument.
return is a function, so only the expression between parentheses are returned. As a result, your integral would not be evaluated because your function would return f(T+x)
The first argument to integrate should be toIntegrate, not toIntegrate(T-y)
mprime will return infinity for u=t, so the limits may need to be adjusted.
a = 3
b = 10
t = 2.6
mprime = function(x){
return (1/x)
}
f = function(x){
ifelse(a <= x & x <= b,1/(b-a),0)
}
toIntegrate = function(u,x,t){
return (f(u + x)*mprime(t-u))
}
solution = function (x, t){
return(f(t + x) + integrate(toIntegrate, 0, t,x=x,t=t,stop.on.error = F)$value)
}
solution(5,T)

Error: object of type 'NoneType' has no len() while implemeting Merge Sort recursively

I'm trying to implement merge sort using python 3.7. For that I've written a merge() function and a recursive sort() function. Here sort() function breaks a list until it has one element. But the problem is the interpreter cannot recognize the arguments m and n of the merge function as lists and hence showing the following error:
def merge(m, n):
x = y = 0
v = []
while x < len(m) and y < len(n):
if m[x] < n[y]:
v.append(m[x])
x = x + 1
elif m[x] > n[y]:
v.append(n[y])
y = y + 1
else:
v.append(m[x])
x, y = x + 1, y + 1
while x < len(m):
v.append(m[x])
x = x + 1
while y < len(n):
v.append(n[y])
y = y + 1
return v
def sort(a):
if len(a) == 1:
return a
else:
merge(sort(a[:len(a) // 2]), sort(a[len(a) // 2:]))
x = list(range(10, 0, -1))
sort(x)
print(x)
Expected result id the sorted list.
But python is showing this error:
Traceback (most recent call last):
File "", line 1, in
sort(x)
File "", line 5, in sort
merge(sort(a[:len(a) // 2]), sort(a[len(a) // 2:]))
File "", line 5, in sort
merge(sort(a[:len(a) // 2]), sort(a[len(a) // 2:]))
File "", line 5, in sort
merge(sort(a[:len(a) // 2]), sort(a[len(a) // 2:]))
File "", line 4, in merge
while x < len(m) and y < len(n):
TypeError: object of type 'NoneType' has no len()
The point is that your sort function does return a if len(a) == 1 but does not return anything if len(a) != 1. It should be return merge(…) instead of just merge(…) in the else part of your sort.
Fixes noted in comments. As an alternative, a one time allocation of a working array could be done and the merge sort would just use indexing as opposed to making multiple copies of the array.
def merge(m, n):
x = y = 0
v = []
while x < len(m) and y < len(n):
if m[x] <= n[y]: # fix
v.append(m[x])
x = x + 1
else:
v.append(n[y])
y = y + 1
while x < len(m):
v.append(m[x])
x = x + 1
while y < len(n):
v.append(n[y])
y = y + 1
return(v)
def sort(a):
if len(a) == 1:
return(a)
else:
return(merge(sort(a[:(len(a)//2)]), sort(a[len(a)//2:])))
# test sort
x = list(range(10, 0, -1))
x = sort(x) # fix
print(x)

How can I use universal and existential quantification in julia?

I want to code domination definition in Julia. x dom y. x , y are 2 vectors.
b=all(x<=y) && any(x<y)
would you please help me. How can I code this concept in Julia?
Thank you
The simplest approach can be almost like you have specified it:
dom(x, y) = all(x .<= y) && any(x .< y)
You could also use a loop e.g. like this:
function dom(x::AbstractVector, y::AbstractVector)
#assert length(x) == length(y)
wasless = false
for (xi, yi) in zip(x, y)
if xi < yi
wasless = true
elseif xi > yi
return false
end
end
return wasless
end

Resources