Turn function into a lambda function

Question:

I have a variables that I am trying to turn into a lambda function but I am struggling to get the input variable to work in the lambda expression.

My variables are:

function_name = 'add'
inpt = 'a,b,c'

and I want the output to be abc * 5 (a,b,c,a,b,c,a,b,c). However it is important that I use the variables rather than simply typing this.

I have tried to use a dictionary as such:

my_dict = {}
my_dict[function_name] =lambda inpt: inpt*5

However the output is a lambda function and I still have to manually enter the value of inpt instead of it taking the variable.

I am fairly new to programming so I may have misunderstood how the lambda function works. Any help would be appreciated.

Asked By: geds133

||

Answers:

Just don’t give the lambda a parameter:

function_name = 'add'
inpt = 'a,b,c'

my_dict = {}
my_dict[function_name] = lambda: inpt * 5  # Don't say that the lambda takes a inpt argument

>>> my_dict[function_name]()  # Now we don't need to supply that here
'a,b,ca,b,ca,b,ca,b,ca,b,c'

I’ll note that the output isn’t technically correct, but that’s not the main point here. You could try using ", ".join on a list of ['a', 'b', 'c'] after using list multiplication to get a better result.

Answered By: Carcigenicate
inpt = 'a,b,c'
func = lambda inpt: ''.join(inpt.split(','))
d = tuple(func(inpt*5))
Answered By: user20224206
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.