I'd like to read a lambda function I created as a string, after I created it.
For example,
func = lambda num1,num2: num1 + num2
I'd like to read func as:
'lambda num1,num2: num1 + num2'
Is there a way to accomplish this or even read any part of the lambda function?
Edit: Changed my first answer as I misunderstood the question. This answer is borrowed from a number of other uses, however I have completed the code to only display the part of the string that you want.
import inspect
func = lambda num1,num2: num1 + num2
funcString = str(inspect.getsourcelines(func)[0])
funcString = funcString.strip("['\\n']").split(" = ")[1]
print funcString
Outputs the following string:
lambda num1,num2: num1 + num2
You can use getsourcelines from the inspect module to do this
This function returns as a list all of the lines of the definition of any function, module, class or method as well as the line number at which it was defined.
For example:
import inspect
f = lambda x, y : x + y
print inspect.getsourcelines(f)[0][0]
Will output the definition of the function as:
f = lambda x, y: x + y
You can use Python's eval() function:
>>> func = eval('lambda num1,num2: num1 + num2')
>>> func
<function <lambda> at 0x7fe87b74b668>
To evaluate any expression and return the value.
You can use Python's inspect module to get the desired code as a list of strings:
#!/usr/bin/env python3
# coding: utf-8
import inspect
func = lambda num1, num2: num1 + num2
def f():
a = 1
b = 2
return a + b
def get_code_as_string(passed_func):
return inspect.getsourcelines(passed_func)
if __name__ == '__main__':
# feed a lambda function
print(get_code_as_string(func))
#feed a normal function
print(get_code_as_string(f))
The output is as follows:
(['func = lambda num1, num2: num1 + num2\n'], 6)
(['def f():\n', ' a = 1\n', ' b = 2\n', ' return a + b\n'], 8)
As you can see inspect.getsourcelines() returns a tuple of a list and an integer. The list contains all the lines of the function passed to inspect.getsourcelines() and the integer represents the line number in which the provided functions starts.
Related
This question already has answers here:
Construct callable function from string [duplicate]
(3 answers)
Closed 12 months ago.
I have four subroutines to multiply, divide, add and subtract 2 numbers which I will ask the user for.
My unfinished code is:
def multiply(a, b):
print(f"{a} x {b} = {a*b}")
def divide(a, b):
print(f"{a} รท {b} = {a*b}")
num1 = int(input("What is the first number?\n"))
num2 = int(input("What is the second number?\n"))
calculation = input("What calculation would you like to perform? [multiply, divide]\n")
calculation(num1, num2)
but it gives TypeError: 'str' object is not callable
Is it necessary to use if statements like:
if calculation == 'multiply':
multiply()
elif calculation == 'divide':
divide()
for all four subroutines or can I use the variable calculation to substitute for the function name.
Use a dictionary to hold your functions
funcs = {'multiply': multiply, 'divide': divide}
and then access funcs[calculation].
... or if you have a DRY fetish:
funcs = {f.__name__: f for f in [multiply, divide]}
Demo:
>>> funcs['multiply'](3, 4)
3 x 4 = 12
You could also access the globals() dict
>>> globals()['multiply'](3, 4)
3 x 4 = 12
but this is not such a good idea because the function to call comes from user input and who knows what weird callables are in globals().
Bonus: safeguarding against bad input
from functools import partial
def notfound(fname, *_, **__):
print(f'function {fname!r} not found')
Usage:
>>> calculation = 'multiply'
>>> funcs.get(calculation, partial(notfound, calculation))(3, 4)
3 x 4 = 12
>>> calculation = 'none'
>>> funcs.get(calculation, partial(notfound, calculation))(3, 4)
function 'none' not found
I wanted to calculate the the factorial of a number using python lambda function without recursion.
I did without lamda function
def factorial_number(num):
fact = 1
while(num>=1):
fact = num* fact;
num = num-1
return fact
factorial_number(5)
I have tried the below code without recursion(using lambda).
factorial_number = lambda num : 1 while(num>=1) fact = fact*num num = num-1 return fact
The above code doesn't work.
Error:
File "<ipython-input-1-62f7b66fbfd2>", line 1
factorial_number = lambda num : 1 while(num>=1) fact = fact*num num = num-1 return fact
^
SyntaxError: invalid syntax
But i want to implement using lamda function, without in-built functions and without recursive method. so that i can learn more how to use lamba funcitons effectively.
please help me with the code.
def factorial(n):
t = 1
for i in range(n, 1, -1):
t *= i
return t
>>> factorial(4)
24
You can use functools.reduce()
from functools import reduce
num = int(input('Enter number: '))
fact = lambda num: reduce(lambda x, y: x * y, range(1, num+1))
print(f'{num}! = {fact(num)}')
You can simply use math.factorial.
import math
fctrl = lambda: math.factorial(x)
or
from math import factorial
fctrl = lambda: factorial(x)
Im trying to figure out ,how this code works without calling the function (num2)?
Example:
def num1(x):
def num2(y):
return x * y
return num2
res = num1(10)
print(res(5))
Output:
50
It does call num2. That's what gets assigned to res, so res(5) calls it.
It might be slightly clearer if you rewrite num1 to use a lambda expression (which is possible due to the simple nature of the function being defined and returned):
def num1(x):
return lambda y: x * y
res = num1(10) # res is a function that multiplies its argument by 10
print(res(5))
If you try to print res without giving any argument in it, you can see it behaves like a function shortly points a function address ;
def num1(x):
def num2(y):
return x * y
return num2
res = num1(10)
print(res)
print(res(5))
Output;
<function num1.<locals>.num2 at 0x02DDBE38>
50
I commented this to explain the functions.
# Defined function named num1 taking input 'x'
def num1(x):
# Function 'num2' defined inside 'num1' taking input 'y'
def num2(y):
# Second function returning num1 input * num2 input
return x * y
# First function returning num2 is returned first
return num2
# this is a variable for inputting to the nested functions.
# res = num1(num2)
res = num1(10)
# This is initializing num1 as 5
print(res(5))
# But it would be way easier...
def nums(x,y):
return x * y
print(nums(5,10))
I would like to build the sum of functions in python. However, I don't know upfront the length of the sum. All functions are of similar type, i.e. having one input and same output type. For two something like this would work
In [180]: def H(f, g):
...: def _h(x):
...: return f(x) + g(x)
...: return _h
However, I would like to have something which is generic in the sense that I could write H(*args) and it returns me the sum of all function in args (also working for just one).
Am I correct that this is the only way to build sum of functions? I can't write something like h = f+g for two function ?
It is probably easier to write something that is extendable. And you should use the built-in function sum to do the actual summing. This returns a generator that applies each function to the input x:
def map_funcs(x, *funcs):
return (f(x) for f in funcs)
funcs = lambda x: x + 1, lambda x: x**2
x = 10
print(sum(map_funcs(x, *funcs)))
If you want to you can also make it a wrapper which returns something callable, similar to what you've already got:
def map_funcs(*funcs):
def wrapper(x):
return (f(x) for f in funcs)
return wrapper
funcs = lambda x: x + 1, lambda x: x**2
x = 10
print(sum(map_funcs(*funcs)(x)))
# 111
Yes, it's possible. You have to use the sum() builtin function that return the sum of all values in the given list. Before that, you of course have to compute the list of all the functions givent to H() run with the correct parameter:
def power_two(x):
return x**2
def plus_20(x):
return x + 20
def H(*args):
def _h(x):
_results = [f(x) for f in args]
return sum(_results)
return _h
if __name__ == '__main__':
the_func = H(power_two, plus_20)
final_result = the_func(2)
print("(2^2) + (2+20) = %s" % the_func(2))
print("(3^2) + (3+20) = %s" % the_func(3))
Returns:
(2^2) + (2+20) = 26
(3^2) + (3+20) = 32
Try this:-
def H(*args):
def _h(x):
for func in args:
z += func(x)
return z
return _h
Just loop around the functional arguments and then sum it. I guess simple?
I hope it helps!
So I'm creating a program that gives random outputs including addition, subtraction, multiplication and division. In order to remove repeating any code I am attempting to narrow the function down to essentially
sum(operand)
a = random.randint(1, 10)
b = random.randint(1, 10)
c = a + operand + b
print c
I am looking to be able to call say sum(*) so c would return the product of a and b.
I feel like this is a concatenation issue
Here I am using sum as an arbitrary name. The function should be able to add, subtract, multiply and divide, all depending on the operand passed through. For example, if "-" is passed through, c would be a - b, if "/" was passed through, c would be a / b
Thanks
import random
def operate(a, b, operand):
return eval(str(a) + operand + str(b))
"operand" is a string.
operate(50,5,"*") would return 250, for example.
The eval() function takes a string and executes it. This converts a and b to strings, so in the example given, the resulting string would be "50*5", which would then be executed by eval().
Python:: Turn string into operator
This question basicially asks the same allthough with a different starting point.
From the accepted answer by Annon:
import operator
ops = { "+": operator.add, "-": operator.sub } # etc.
print ops["+"](1,1) # prints 2
Reference to imported operator class:
https://docs.python.org/3.6/library/operator.html
You can try this:
import random
def produce(func):
a = random.randint(1, 10)
b = random.randint(1, 10)
c = func(a,b)
return c
def sum(a,b):
return a+b
def multiply(a,b):
return a*b
def substract(a,b):
return a-b
operands = [
sum,
multiply,
substract,
]
# tests
print "\n".join(["%s: %d" % ( op.__name__, produce(op) ) for op in operands ])
Sample output:
sum: 14
multiply: 45
substract: 7
Unified solution (for int numbers, as example) emulating numeric objects and calling __add__, __sub__, __mul__ and floordiv methods:
def do_arith_operation(a, b, op):
a = int(a).__int__()
b = int(b).__int__()
operators = {'+': '__add__', '-': '__sub__', '*': '__mul__', '/': '__floordiv__'}
return getattr(a, operators[op])(b)
print(do_arith_operation(10, 2, '/'))
The output:
5
int(a).__int__() will create an instance of class <class 'int'>
__add__, __sub__, __mul__ and floordiv methods:
each method takes two objects (the operands of +|-|*|/|) as arguments and returns the result of computation
https://docs.python.org/3/reference/datamodel.html#emulating-numeric-types