IVT Theorem Calculator in Python - python

I am having a problem.
def f(x):
function = input("Enter yoru Function: ")
return function
a = -1
b = 2
a_Applied = f(a)
b_Applied = f(b)
if a_Applied < 0 and b_Applied > 0:
print "IVT Applies."
elif a_Applied > 0 and b_Applied < 0:
print "IVT Applies"
else:
print "IVT Does Not Apply"
This is my current code. I am trying to let the user make a function in line 2. However this breaks the program because it is a string. How do I get it to not be a string, and instead for it to be able to take a function.
Ex.
User inputs "2*x + 1"
In a perfect world the program then runs 2(a) +1 and 2(b) + 1 and then compares them using the if statement. Because the input is a string ti doesn't work.
Any help?

Use lambda expression and eval function. Like this.
def read_user_function():
function_str = input("Enter your Function: ")
return lambda x: eval(function_str, { 'x' : x })
Call user function by
f = read_user_function()
print(f(2))
Here is a demo https://repl.it/ITuU/2.
Explanation
The function above, read_user_function returns a lambda expression, basically a function, that will evaluate the user's input with the variable, sort of like a parameter, x set to the x value that is passed to the lambda expression. This can get confusing if your new to this sort of thing but just think of read_user_function as returning an anonymous function that accepts a single argument and its body equals eval(function_str, { 'x' : x })
Warning
This is a quick and dirty solution to evaluating mathematical expression. The function would execute any valid python code and not only mathematical expression. This may be dangerous if your application is sensitive - you wouldn't want the user executing custom code.

What you're asking to do is very hard (in general). You'd need to define rigorous semantics for all your supported operations (for example, is power ^ or is it ** like you'd do in python?).
The sympy library has a start on this for you. If you assume your input is a polynomial, for example:
import sympy
y = sympy.Poly("x^2 + 2*x + 1")
print(y(3))
# outputs 16
sympy also has the advantage that it will accept "python-like" input as well:
import sympy
y = sympy.Poly("x**2 + 2*x + 1")
print(y(3))
Note that sympy is not limited to polynomials, just included them here as an example because polynomials are relatively simple.

Related

Python - Define a function based on user's input

I have a function taking a function and a float as inputs, for example
def func_2(func, x):
return func(x)
If a function is defined in advance, such as
def func_1(x):
return x**3
then the following call works nicely
func_2(func_1,3)
Now, I would like the user to be able to input the function to be passed as an argument to func_2.
A naive attempt such as
print("enter a function")
inpo = input()
user types e.g. x**3
func_2(inpo)
returns an error as a string is not callable.
At the moment I have a workaround allowing user to only input coefficients of polynomials, as in the following toy example
def funcfoo (x,a):
return x**a
print("enter a coefficient")
inpo = input()
funcfoo(3,int(inpo))
it works as I convert the input string to an integer, which is what the function call expects.
What is the the correct type to convert the input function, to work as first argument of func_2 ?
I think you're looking for the eval() function. This will change a string to a function.
For instance:
x = 3
string = 'x + 3'
eval(string)
# Returns 6
This does require you to modify your initial function a bit. This would work:
def func_2(func, x):
func_new = func.replace('x', str(x))
return eval(func_new)
inpo = 'x + 3'
func_2(inpo, 3)

Lambda function containing if statement

Is there any way how to code recursive function containing if with lamba?
Is possible to rewrite this using lambda.
def factorial(x):
if x <= 1:
return 1
return x * factorial(x - 1)
print(factorial(5))
No, or at least not without assigning the function to a variable and then using that name to call it. But you still cannot use any statements in the function.
In any case, don't do that. A lambda function is exactly like a normal def function in Python besides the restriction that it cannot contain statements.
The only reason to use a lambda in Python is to avoid defining an named function if you just need a simple callable returning some value.
Yes, it is possible for this specific case.
>>> factorial = lambda x: 1 if x < 1 else x * factorial(x - 1)
>>> factorial(5)
120
I wouldn't recommend it though. A standard function definition seems far more readable to me.
>>> l = lambda i: 1 if i<=1 else i * l(i-1)
>>> l(5)
120
>>> 5*4*3*2*1
120

I cannot understand function comparisons in Python

I am using the Canopy IDE. I am a beginner in Python. I was taking the edX online course where I stumbled upon this code:
def a(x,y,z):
if x:
return y
else:
return z
def b(p,r):
return a(p>r,p,r)
print a(3>2,a,b)
I cannot understand how the statement a(3>2,a,b) works. In essence, how function comparison works in python. When I executed the code in my IDE, it gave the following output.
<function a at 0x00000000088F4198>
Your call:
a(3>2, a, b)
Resulted in parameter 'a' being returned. Parameter a is the function used to perform comparison:
def a(x,y,z):
if x:
return y
else:
return z
Default string representation of a function is:
<function (name) at 0x(address in memory)>
Try running function a() with different arguments, like
a(3>2, "Greater", "Smaller")
Or use Python ternary operator:
result = "Greater" if 3 > 2 else "Smaller"

How can I pass functions or operators as arguments to a function in Python?

...while still leaving it executable within the function.
The idea behind this is I want to create a summation function. Here's what I have so far:
def summation(n, bound, operation):
if operation is None and upper != 'inf':
g = 0
for num in range(n, limit + 1):
g += num
return g
else:
pass
But summations are most often about infinite convergent series (for which I use 'inf'), with operations applied to each term. Ideally, I'd like to be able to write print summation(0, 'inf', 1 / factorial(n)) and get the mathematical constant e, or def W(x): return summation(1, 'inf', ((-n) ** (n - 1)) / factorial(n)) to get the Lambert W function.
All that comes to my mind is passing the appropriate arithmetic as a string and then using the exec statement to execute it. But I don't think that would accomplish the whole thing, and it's obviously dangerous to use exec with possibly user-entered code.
In Python, functions are first-class, which is to say they can be used and passed around like any other values, so you can take a function:
def example(f):
return f(1) + f(2)
To run it, you could define a function like this:
def square(n):
return n * n
And then pass it to your other function:
example(square) # = square(1) + square(2) = 1 + 4 = 5
You can also use lambda to avoid having to define a new function if it's a simple expression:
example(lambda n: n * n)

Python functions within lists

So today in computer science I asked about using a function as a variable. For example, I can create a function, such as returnMe(i) and make an array that will be used to call it. Like h = [help,returnMe] and then I can say h1 and it would call returnMe("Bob"). Sorry I was a little excited about this. My question is is there a way of calling like h.append(def function) and define a function that only exists in the array?
EDIT:
Here Is some code that I wrote with this!
So I just finished an awesome FizzBuzz with this solution thank you so much again! Here's that code as an example:
funct = []
s = ""
def newFunct(str, num):
return (lambda x: str if(x%num==0) else "")
funct.append(newFunct("Fizz",3))
funct.append(newFunct("Buzz",5))
for x in range(1,101):
for oper in funct:
s += oper(x)
s += ":"+str(x)+"\n"
print s
You can create anonymous functions using the lambda keyword.
def func(x,keyword='bar'):
return (x,keyword)
is roughly equivalent to:
func = lambda x,keyword='bar':(x,keyword)
So, if you want to create a list with functions in it:
my_list = [lambda x:x**2,lambda x:x**3]
print my_list[0](2) #4
print my_list[1](2) #8
Not really in Python. As mgilson shows, you can do this with trivial functions, but they can only contain expressions, not statements, so are very limited (you can't assign to a variable, for example).
This is of course supported in other languages: in Javascript, for example, creating substantial anonymous functions and passing them around is a very idiomatic thing to do.
You can create the functions in the original scope, assign them to the array and then delete them from their original scope. Thus, you can indeed call them from the array but not as a local variable. I am not sure if this meets your requirements.
#! /usr/bin/python3.2
def a (x): print (x * 2)
def b (x): print (x ** 2)
l = [a, b]
del a
del b
l [0] (3) #works
l [1] (3) #works
a (3) #fails epicly
You can create a list of lambda functions to increment by every number from 0 to 9 like so:
increment = [(lambda arg: (lambda x: arg + x))(i) for i in range(10)]
increment[0](1) #returns 1
increment[9](10) #returns 19
Side Note:
I think it's also important to note that this (function pointers not lambdas) is somewhat like how python holds methods in most classes, except instead of a list, it's a dictionary with function names pointing to the functions. In many but not all cases instance.func(args) is equivalent to instance.__dict__['func'](args) or type(class).__dict__['func'](args)

Categories