What is the lambda function doing in this code? [duplicate] - python

This question already has answers here:
python max function using 'key' and lambda expression
(6 answers)
Closed 6 years ago.
I have the following code for a greedy implementation of the traveling salesman problem. I can't wrap my head around what exactly the lambda function does in this code.
def distance(p1, p2):
return ((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2) ** 0.5
def tsp_greedy(points, start=None):
if start is None:
start = points[0]
to_visit = points
path = [start]
to_visit.remove(start)
while to_visit:
closest = min(to_visit, key=lambda x: distance(path[-1], x))
path.append(closest)
to_visit.remove(closest)
return path
I realize it's creating an anonymous function which x gets passed into. But I'm not sure what is getting passed into this function. What is x?

closest becomes to_visit[i] such that
distance(path[-1], to_visit[i]) =
min(distance(path[-1], to_visit[0]), distance(path[-1], to_visit[1]), ...)
In other words, the lambda function makes comparison not by to_visit[i] but by distance(path[-1], to_visit[i]).

Related

Want to know how lamda function work in python [duplicate]

This question already has answers here:
Lambda in a loop [duplicate]
(4 answers)
Closed 10 months ago.
I'm trying to understand the lambda function in python and got this.
When I store the instance of lambda function in a Dict. It gives the expected result inside of the loop. But outside of the loop, it always stored the last instance, I think.
Can someone explain why this happening? and how the lambda function actually works when we store their instance.
Code:
d = {}
for x in range(4):
d[x] = lambda n: str(n*x)
print(d[x](1))
print(d[1](2))
print(d[2](2))
print(d[3](2))
Output:
0
1
2
3
6
6
6
given some x these 2 functions are equivalent:
f1 = lambda n: str(n * x)
def f2(n):
return str(n * x)
all you are doing in addition to that is to put several functions (for several values of x) in a dictionary.

Create a new function from a list of functions [duplicate]

This question already has answers here:
Apply a list of Python functions in order elegantly
(2 answers)
Closed 2 years ago.
Consider a few simple functions:
add2 = lambda x: x+2
add3 = lambda x: x+3
add4 = lambda x: x+4
And having them stored in a list:
funcs = [add2, add3, add4]
Is there a way, how to create a new function, which applies all the given ones?
Not working solution:
f = funcs[0]
for g in funcs[1:]:
f = lambda x: g(f(x))
This does not work, since after trying to call the create function f(0), I get RecursionError: maximum recursion depth exceeded, which I don't completely understand.
The solution for the question Apply a list of Python functions in order elegantly does not work for my problem.
I don't want to get to the result (yet), I want to construct a new function
from functools import reduce
result = reduce(lambda res, f: f(res), funcs, val)
However, it should work with a combination of partial.
Working solution with functools:
import functools
f = functools.partial(functools.reduce, lambda res, f: f(res), funcs)
Working solution (without lambdas):
def _inner(x):
for f in funcs:
x = f(x)
return x
Calling _inner(0) returns correctly 9.

How to call another function from a function [duplicate]

This question already has answers here:
How do you call a function in a function?
(4 answers)
Closed 2 years ago.
My First function is addition of program
def addn(x,y):
return (x + y)
My second function is output got from the first function + 2
def addn2(x,y)
return (x+y+2)
Instead of above searching for anything like below, with out re writing everything in the second function
def addn3(x,y):
return (addn + 2)
The parameters are important:
def addn3(x, y):
return (addn(x, y) + 2)

How to access closed over variables given only the closure function? [duplicate]

This question already has answers here:
Reflect / Inspect closed-over variables in Python
(3 answers)
Closed 3 years ago.
In the following example:
def speak(volume):
def whisper(text):
print(text.lower() + ('.' * volume))
def yell(text):
print (text.upper() + ('!' * volume))
if volume > 1:
return yell
elif volume <= 1:
return whisper
func = speak(volume=10)
func('hello')
HELLO!!!!!!!!!! # <== obviously `10` is stored in `func` somewhere
Given func, how would I get the "volume"? Is there something within the func namespace which gives the value of 10? I thought perhaps it would be in func.__globals__ or func.__dict__ but it's in neither.
Below (the code below return 10)
func.__closure__[0].cell_contents

How can I build a iterated function using the return value as the input parameter [duplicate]

This question already has answers here:
Apply a list of Python functions in order elegantly
(2 answers)
Closed 3 years ago.
For some function f and variable a,
b_1 = f(a),
b_2 = f(b_1),
b_3 = f(b_2)
...
b_n = f(b_n-1)
I would like to do n-times by iterated method. In a functional way, this is accomplished by a function composition.
f...(f(f((a)))
You can achive your result by recusion
you can refer below pesudo code
#define f(a):
# do computation
# if terminating condition
# then return the computed result
#else
# return f(computed result)

Categories