I'm stuck at higher-order functions in python. I need to write a repeat function repeat that applies the function f n times on a given argument x.
For example, repeat(f, 3, x) is f(f(f(x))).
This is what I have:
def repeat(f,n,x):
if n==0:
return f(x)
else:
return repeat(f,n-1,x)
When I try to assert the following line:
plus = lambda x,y: repeat(lambda z:z+1,x,y)
assert plus(2,2) == 4
It gives me an AssertionError. I read about How to repeat a function n times but I need to have it done in this way and I can't figure it out...
You have two problems:
You are recursing the wrong number of times (if n == 1, the function should be called once); and
You aren't calling f on the returned value from the recursive call, so the function is only ever applied once.
Try:
def repeat(f, n, x):
if n == 1: # note 1, not 0
return f(x)
else:
return f(repeat(f, n-1, x)) # call f with returned value
or, alternatively:
def repeat(f, n, x):
if n == 0:
return x # note x, not f(x)
else:
return f(repeat(f, n-1, x)) # call f with returned value
(thanks to #Kevin for the latter, which supports n == 0).
Example:
>>> repeat(lambda z: z + 1, 2, 2)
4
>>> assert repeat(lambda z: z * 2, 4, 3) == 3 * 2 * 2 * 2 * 2
>>>
You've got a very simple error there, in the else block you are just passing x along without doing anything to it. Also you are applying x when n == 0, don't do that.
def repeat(f,n,x):
"""
>>> repeat(lambda x: x+1, 2, 0)
2
"""
return repeat(f, n-1, f(x)) if n > 0 else x
Related
I would like to find an approximate value for the number pi = 3.14.. by using the Newton method. In order to use it also for some other purpose and thus other function than sin(x), the aim is to implement a generic function that will be passed over as an argument. I have an issue in passing a function as an argument into an other function. I also tried lambda in different variations. The code I am showing below produces the error message: IndexError: list index out of range. I will appreciate your help in solving this issue and eventually make any suggestion in the code which may not be correct. Thanks.
from sympy import *
import numpy as np
import math
x = Symbol('x')
# find the derivative of f
def deriv(f,x):
h = 1e-5
return (lambda x: (f(x+h)-f(x))/h)
def newton(x0,f,err):
A = [x0]
n = 1
while abs(A[n]-A[n-1])<=err:
if n == 1:
y = lambda x0: (math.f(x0))
b = x0-y(x0)/(deriv(y,x0))
A.append(b)
n += 1
else:
k = len(A)
xk = A[k]
y = lambda xk: (math.f(xk))
b = newton(A[k],y,err)-y(newton(A[k],y,err))/deriv(y,k)
A.append(b)
n += 1
return A, A[-1]
print(newton(3,math.sin(3),0.000001))
I don't know why you use sympy because I made it without Symbol
At the beginning you have to calculate second value and append it to list A and later you can calculate abs(A[n]-A[n-1]) (or the same without n: abs(A[-1] - A[-2])) because it needs two values from this list.
Other problem is that it has to check > instead of <=.
If you want to send function sin(x) then you have to use math.sin without () and arguments.
If you want to send function sin(3*x) then you would have to use lambda x: math.sin(3*x)
import math
def deriv(f, x, h=1e-5):
return (f(x+h) - f(x)) / h
def newton(x0, f, err):
A = [x0]
x = A[-1] # get last value
b = x - (f(x) / deriv(f, x)) # calculate new value
A.append(b) # add to list
while abs(A[-1] - A[-2]) > err: # it has to be `>` instead of `<=`
x = A[-1] # get last value
b = x - (f(x) / deriv(f, x)) # calculate new value
A.append(b) # add to list
return A, A[-1]
# sin(x)
print(newton(3, math.sin, 0.000001)) # it needs function's name without `()`
# sin(3*x)
print(newton(3, lambda x:math.sin(3*x), 0.000001))
# sin(3*x) # the same without `lambda`
def function(x):
return math.sin(3*x)
print(newton(3, function, 0.000001))
Result:
([3, 3.1425464414785056, 3.1415926532960112, 3.141592653589793], 3.141592653589793)
([3, 3.150770863559604, 3.1415903295877707, 3.1415926535897936, 3.141592653589793], 3.141592653589793)
EDIT:
You may write loop in newton in different way and it will need <=
def newton(x0, f, err):
A = [x0]
while True:
x = A[-1] # get last value
b = x - (f(x) / deriv(f, x)) # calculate new value
A.append(b) # add to list
if abs(A[-1] - A[-2]) <= err:
break
return A, A[-1]
When my function foo generating a new element, I want to reuse the output and put it in foo n-times. How can I do it?
My function:
def foo(x):
return x + 3
print(foo(1))
>>>4
For now. I'm using this method:
print(foo(foo(foo(1))))
There are a couple ways to do what you want. First is recursion, but this involves changing foo() a bit, like so:
def foo(x, depth):
if depth <= 0:
return x
return foo(x+3, depth-1)
and you'd call it like foo(1, n)
The other way is with a loop and temp variable, like so
val = 1
for _ in range(0, n):
val = foo(val)
Use a loop for this:
value = 1
for i in range(10):
value = foo(value)
def foo(x,y):
for i in range(y):
x = x + 3
return x
print (foo(10,3))
Output:
19
What you are searching for is called recursion:
def foo(x, n=1):
if n == 0:
return x
return foo(x + 3, n - 1)
Another possible with lambda and reduce
Reduce function
from functools import reduce
def foo(x):
return x + 3
print(reduce(lambda y, _: foo(y), range(3), 1))
You will get 10 as result
# y = assigned return value of foo.
# _ = is the list of numbers from range(3) for reduce to work
# 3 = n times
# 1 = param for x in foo
I came across the following homework problem:
My code for this problem was marked wrong and when I viewed the suggested solution, I couldn't understand where I went wrong. I ran the codes of both functions in Python IDLE compiler only to see that both functions return the same output as seen below:
>>> def dual_function(f,g,n): #Suggested solution
def helper(x):
f1,g1 = f,g
if n%2==0:
f1,g1=g1,f1
for i in range(n):
x=f1(x)
f1,g1=g1,f1
return x
return helper
>>> def dual_function_two(f,g,n): #My solution
def helper(x):
if n%2==0:
for i in range (n):
if i%2==0:
x = g(x)
else:
x = f(x)
else:
for i in range(n):
if i%2==0:
x = f(x)
else:
x = g(x)
return x
return helper
>>> add1 = lambda x: x+1
>>> add2 = lambda x: x+2
>>> dual_function(add1,add2,4)(3)
9
>>> dual_function_two(add1,add2,4)(3)
9
>>>
I would appreciate it if someone could identify the mistake in my solution. Thank you.
The suggested solution is needlessly complex. Countless reassignments of variables and a loop are a recipe for a headache. Here's a simplified alternative -
def dual (f, g, n):
if n == 0:
return lambda x: x
else:
return lambda x: f(dual(g, f, n - 1)(x))
add1 = lambda x: 1 + x
add2 = lambda x: 2 + x
print(dual(add1,add2,4)(3))
# 9
# (1 + 2 + 1 + 2 + 3)
print(dual(add1,add2,9)(3))
# 16
# (1 + 2 + 1 + 2 + 1 + 2 + 1 + 2 + 1 + 3)
print(dual(add1,add2,0)(3))
# 3
The reason this works is because in the recursive branch, we call dual with swapped arguments, dual(g,f,n-1). So f and g change places each time as n decrements down to 0, the base case, which returns the identity (no-op) function.
A slightly less readable version, but works identically -
def dual (f, g, n):
return lambda x: \
x if n == 0 else f(dual(g, f, n - 1)(x))
Could any one explain the flow of this program by giving an example?
id_ = lambda x:x
// would return the number (id_(1) would return 1)
zero=map(number,0)//should return number= lambda 0: lambda 0:f(0)
So I am not able to interpret:
number = lambda x: lambda f=id_: f(x)
plus = lambda x: lambda y: y + x
id_ = lambda x: x
number = lambda x: lambda f=id_: f(x)
zero, one, two, three, four, five, six, seven, eight, nine = map(number, range(10))
plus = lambda x: lambda y: y + x
minus = lambda x: lambda y: y - x
times = lambda x: lambda y: y * x
divided_by = lambda x: lambda y: y / x
Calculations using functions:
one(plus(one()))
> 2
number():
- expects a number "A"
- returns a function "F" that expects a single argument function (or if not provided it uses "id_" by default)
When both arguments are provided the function number() gets evaluated and applies the function F to the number A
# Example 1: returns only 3 (applies "id_" by default)
print(number(3)())
Prints:
3
And when a function is provided:
def inc(x):
return x + 1
# Example 2: applies a single argument function to the number 3
print(number(3)(inc))
Which returns:
4
So now the second function you are interested in:
plus():
- expects a number
- returns a function that accept another number
When both arguments are provided the function is evaluated and returns their sum.
# Example:
print(plus(3)(4))
Prints:
7
Using the example you used in the comments:
one(plus(one()))
Starting from the innermost expression we get:
one() == 1 because one() == number(1)(f=id_) == _id(1)
Second call to plus(1) would return lambda y: y+1
Applied to the result from first step, plus(one()) == plus(1) == lambda y: y+1
So it means that plus(one()) is (in other words: "returns") itself a function and is equivalent to:
def plus_one(y):
return y + 1
Last step:
one(plus(one())) == one(plus_one) == number(1)(f=plus_one) == plus_one(1) == 1 + 1 == 2
If the lambda syntax bothers you, you can rewrite them for increased clarity (?) into full functions accordingly:
def id_(x):
return x
def number(x):
def inner(f=id_):
return f(x)
return inner
def one(f=id_):
return f(1)
def plus(x):
def add_to_x(y):
return y + x
return add_to_x
add_one = plus(one())
assert one() == number(1)(f=id_) == id_(1) == 1
assert add_one(2) == plus(1)(2) == 3
assert plus(one())(4) == plus(1)(4) == 5
assert one(plus(one())) == one(add_one) == 2
def fib(a, b, f):
fib must generate (using yield) the generalized Fibonacci
sequence, a and b is first and second element. f is function to get the third element instead of a+b as normal Fibonacci sequence. Use take function(which show below) to test it.
my code is below
def fib(a, b, f):
x = a
y = b
yield x
x, y = y, f(x,y)
fib(x,y,f)
I don't know what is wrong of my code, when I try to test it, it show
"TypeError: 'generator' object is not subscriptable"
the test case is:
take(5, fib(0, 1, lambda x, y: x - y))
It should out put:
[0, 1, -1, 2, -3]
and take function as i write is :
def take(n, iterable):
x = []
if n <= 0:
return x
else:
for i in range (0,n):
x.append(iterable[i])
return x
The message means that generators do not support indexing, so iterable[i] fails. Instead, use the next() function to get the next item from the iterator.
def take(n, iterable):
x = []
if n > 0
itr = iter(iterable) # Convert the iterable to an iterator
for _ in range(n): # Repeat n times
x.append(next(itr)) # Append the next item from the iterator
return x
Also, your fib() function will not work. You should not recurse at the end of the function; instead write a loop that yields a value each iteration.
def fib(a, b, f):
x = a
y = b
while True:
yield x
x, y = y, f(x,y)
You can't index into the results coming from a generator function like fib(). This following avoids that by using zip() with a range() argument. zip() stops automatically when one of its arguments reaches then end.
def fib(a, b, f):
x, y = a, b
while True:
yield x
x, y = y, f(x, y)
def take(n, iterable):
return [] if n <= 0 else [v for _, v in zip(range(n), iterable)]
print( take(5, fib(0, 1, lambda x, y: x-y)) )
Output:
[0, 1, -1, 2, -3]
Fibonacci simplest method you'll ever come across:
a , b =0 , 1
for n in range(100):#any number
print(a)
a = a + b
print (b)
b = b + a
def fibo(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibo(n - 1) + fibo(n - 2)
n = int(input("enter the number: "))
for i in range(n):
print(fibo(i))