Define functions recursively with derivative in Python - python-2.7

How can I define a succession of functions h_k: k=1,2,3,...
by using two known functions f=f(x) and g=g(x) as follows:
h_1=f/g,
h_{k+1}=diff(h_k,x)/g, for k=1,2,3,.....
Note that the new functions have two entries h(k,x)=h_k(x).
I want to do it in Sympy.

If k will always be an explicit integer, just use a Python function:
def h(x, k):
if k == 1:
return f(x)/g(x)
return diff(h(x, k - 1), x)/g(x)
If you want to allow symbolic k (like k = Symbol('k')), subclass sympy.Function
class h(Function):
#classmethod
def eval(cls, x, k):
if k.is_Integer and k.is_positive:
if k == 1:
return f(x)/g(x)
else:
return diff(h(x, k - 1), x)/g(x)
(note that if eval returns None (i.e., it hits the bottom of the function without returning), the function will remain unevaluated.
Note that we check k.is_Integer with a capital I (not k.is_integer). This means that k is an explicit integer, like 1, 2, 3, .... k.is_integer would also be true for Symbol('k', integer=True), but we don't want to evaluate in this case because we don't know which integer it is.

Related

Defining logical operator implies in lua

print("i", "j", "i & j")
for i = 0,1 do
for j=0,1 do
print(i, j, i & j)
end
end
The above code works fine in Lua. It gives the following output.
i j i & j
0 0 0
0 1 0
1 0 0
1 1 1
I want to define another operator implies. It is conditional logical operator. The result p implies q is false only when p is true and q is false.
print("i", "j", "i implies j")
for i = 0,1 do
for j=0,1 do
print(i, j, i implies j)
end
end
I want the above code to work. It should output the following.
i j i implies j
0 0 1
0 1 1
1 0 0
1 1 1
So far I have succeeded in defining implies function but that doesn't seem to be of great use. Of course I can write implies(i,j) but I want operator similar to & or | that I can use. So basic question is to replicate definition of logical operator & or | from lua. Here is the code for implies function (not operator).
function implies(a,b)
if a then
return b
else
return True
end
end
OOP-style calls
This gets rather hacky if it must truly be infix. What about simply using metatables for OOP-ish object:method(params) syntax?
Assuming implies is defined as
local function _implies(a, b)
if a ~= 0 then return b end
return 1
end
this would be implemented as
debug.setmetatable(0, {__index = {
implies = _implies
}})
and used as
i:implies(j)
if you want you a simpler dot syntax instead, consider using currying:
debug.setmetatable(0, {__index = {
implies = function(a) return function(b) return _implies(a, b) end end
}})
used as
i.implies(j)
A more "infix-ish" notation might be achieved by using the __call metamethod, and passing a function name:
debug.setmetatable(0, {__index = {
implies = function(a) return function(b) return _implies(a, b) end end
}, __call = function(self, index) return self[index] end})
(i)("implies")(j)
If implies = "implies", this can even be shortened to (i)(implies)(j).
Hacky, "truly" infix notation
If infix notation is of utmost importance, yet you can't use the available metamethods as they are limited and rather unreadable, you can use even more currying and workarounds to use other metamethods to create operators that seemingly turn your function (at least syntactically) into an infix operator using a "proxy" metatable instead of the function. You can use whatever operators you like; just make sure they suit your needs in terms of associativity and precedency:
local implies_right_hand_mt = {
__mul = function(self, b)
return _implies(self.a, b)
end
}
local implies_left_hand = setmetatable({}, {
__mul = function(a)
return setmetatable({a = a}, implies_right_hand_mt)
end
})
implies = implies_left_hand
The syntax would then be i *implies* j or "i *implies* j" in your example (using the multiplication operator). You could however use all other operators (except the comparison operators) as well, including other arithmetic operators, as implies is not a number but rather a table and may thus override number metamethods.
Side note
Consider using booleans instead of numbers. You'd get two advantages:
Most metamethods aren't used by booleans (especially all arithmetic & bitwise metamethods);
The logic operators not, and and or work; you don't have to use bitwise operators (although those work fine as well).
There are two metamethods available for "number" datatype: __call and __index.
debug.setmetatable(0, {__call = function(a, b) return a~1|b end})
-- Now you can use "(i)(j)" for "i implies j"
print("i", "j", "(i)(j)")
for i = 0,1 do
for j = 0,1 do
print(i, j, (i)(j))
end
end
Lua has no provision for user-defined operators.
CustomOperators
But if i and j were boolean, you could use:
i and j or true
It doesn't work with 0 and 1, because for LUA they are both true!

How can I write an efficient loop to solve this Code Wars problem?

The problem is the following:
This is a problem taken from code wars and titled 'Is my friend cheating?'
. A friend of mine takes a sequence of numbers from 1 to n (where n > 0).
. Within that sequence, he chooses two numbers, a and b.
. He says that the product of a and b should be equal to the sum of all numbers in the sequence, excluding a and b.
. Given a number n, could you tell the numbers he excluded from the sequence?
The function takes the parameter: n (n is always strictly greater than 0) and returns an array or a string of the form:
It happens that there are several possible (a, b). The function returns an empty array (or an empty string) if no possible numbers are found which will prove that my friend has not told the truth!
Example of returned sequence:
removNb(26) should return [(15, 21), (21, 15)]
I have tried a simple loop sequence:
def remov_nb(n):
somme = 0
liste = []
for num in range (n+1):
somme += num
for a in range(n+1):
for b in range(n+1):
if a * b == (somme-a-b):
liste.append((a,b))
return (liste)
and also used itertools:
def remov_nb(n):
from itertools import product
liste = []
somme = sum(x for x in range(1,n+1))
for x,y in product(range(1,n+1), range(1,n+1)):
if (somme - x - y) == (x * y):
liste.append((x,y))
return liste
The function doesn't work on Code Wars for lack of efficiency.
Can someone guide me here?

recursive binary search using python 2.7

Wrote this code in comp sci class and I cant get it to work, it always returns as false every time I run it. Its supposed to be a recursive binary search method... Any idea why it only returns false?
arr = [1,10,12,15,16,122,132,143,155]
def binarysearch(arr,num):
arr2 = []
if (len(arr) == 1):
if (arr[0] == num):
return 1
else:
return 0
for i in range (len(arr)/2):
arr2.append(0)
if (arr[len(arr)/2]>num):
for x in range (len(arr)/2,len(arr)):
arr2[x-(len(arr)/2)]=arr[x]
return binarysearch(arr2,num)
if(arr[len(arr)/2]<num):
for x in range(0, len(arr) / 2 ):
arr2[x] = arr[x]
return binarysearch(arr2, num)
num = raw_input("put number to check here please: ")
if(binarysearch(arr,num)==1):
print "true"
else:
print "false"
You're doing vastly more work than you need to on things that Python can handle for you, and the complexity is masking your problems.
After your base case, you have two if statements, that don't cover the full range—you've overlooked the possibility of equality. Use if/else and adjust the ranges being copied accordingly.
Don't create a new array and copy stuff, use Python's subranges.
Don't keep repeating the same division operation throughout your program, do it once and store the result.
If you want to print True/False, why not just return that rather than encoding the outcome as 0/1 and then decoding it to do the print?
Recall that raw_input returns a string, you'll need to convert it to int.
The end result of all those revisions would be:
def binary_search(arr,num):
if (len(arr) == 1):
return (arr[0] == num)
mid = len(arr) / 2
if (arr[mid] > num):
return binary_search(arr[:mid], num)
else:
return binary_search(arr[mid:], num)
num = int(raw_input("put number to check here please: "))
print binary_search(arr,num)

Write a function that calculates the sum of all values in a list of integers that are both positive and even

The function should accept a single list as a parameter. The function should return an integer value as the result of calculation. If there are no positive and even integer values in the list, your function should return 0.
My current code:
def main():
print (sum_positive_even([1,2,3,4,5]))
print (sum_positive_even([-1,-2,-3,-4,-5]))
print (sum_positive_even([1,3,5,7,9]))
def sum_positive_even(list):
for num in list:
if num < 0:
list.remove(num)
for num in list:
if num % 2 == 1:
list.remove(num)
result = sum(list)
return result
main()
The output should be like:
6
0
0
I'm confused where I should put the 'return 0'.
Thanks TA!
Deleting from a list while you iterate over it is a Bad Idea - it's very easy to get hard-to-track-down bugs that way. Much better would be to build a new list of the items you want to keep. You don't need a special case of returning 0; the general approach should be able to handle that.
Also, it's better not to use list as a variable name in Python, because that's the name of a built-in.
A modification of your approach:
def sum_positive_even(lst):
to_keep = []
for num in lst:
if num > 0 and num % 2 == 0:
to_keep.append(num)
return sum(to_keep)
Since the sum of an empty list is 0, this covers the case where there are no positive even numbers.

Trying to make a recursive call in C++

This is my first question here so be kind :-) I'm trying to make a recursive call here, but I get the following compiler error:
In file included from hw2.cpp:11:
number.h: In member function ‘std::string Number::get_bin()’:
number.h:60: error: no matching function for call to ‘Number::get_bin(int&)’
number.h:27: note: candidates are: std::string Number::get_bin()
string get_bin ()
{
bin = "";
printf("Value is %i\n",val);
if (val > 0)
{
int remainder = val;
printf("remainder is %i\n",remainder);
printf("numbits is %i\n",size);
for (int numbits = size-1;numbits>=0;numbits--)
{
//printf("2 raised to the %i is %i\n",numbits,int(pow(2,numbits)));
printf("is %i less than or equal to %i\n",int(pow(2,numbits)),remainder);
if (int (pow(2,numbits))<=remainder)
{
bin+="1";
remainder -= int(pow(2,numbits));
printf("Remainder set to equal %i\n",remainder);
}
else
{
bin+= "0";
}
}
return bin;
}
else
{
int twoscompliment = val + int(pow(2,size));
return get_bin(twoscompliment);
}
Any thoughts? I know get_bin works for positive numbers.
In the last line you are calling get_bin() with an integer reference argument, but there are no formal parameters in the function signature.
string get_bin ()
return get_bin(twoscompliment);
These are mutually incompatible. I don't see how you can say that code works for positive numbers since it's not even compiling.
You probably need to change the first line to something like:
string get_bin (int x)
but, since you don't actually use the argument, you may have other problems.
If you're using global or object-level variables to do this work, recursion is not going to work, since they different levels will be stepping on each other's feet (unless you do your own stack).
One of the beauties of recursion is that your code can be small and elegant but using local variables is vital to ensure your data is level-specific.
By way of example, examine the following (badly written) pseudo-code:
global product
def factorial (n):
if n == 1:
return 1
product = factorial (n-1)
return n * product
Now that won't work for factorial (7) since product will be corrupted by lower levels. However, something like:
def factorial (n):
local product
if n == 1:
return 1
product = factorial (n-1)
return n * product
will work just fine as each level gets its own copy of product to play with. Of course:
def factorial (n):
if n == 1:
return 1
return n * factorial (n-1)
would be even better.
The function is defined to take no arguments, yet you pass an int.
It looks like you're accessing a global or member variable val. That should probably be converted into the argument.
string get_bin ( int val )
Since you have not declared bin and val in the function I guess they are global.
Now you define the function get_bin() to return a string and not accept anything. But in the recursive call you are passing it an int. Since you want to pass twoscompliment as val for the recursive call you can do:
int twoscompliment = val + int(pow(2,size));
val = twoscompliment; // assign twoscompliment to val
return get_bin();