Friday, 5 October 2018

Can pythons lambda be used to change the inner working of another function?

I have the following code snippet which i needed to (massively) speed up. As is, it's hugely inefficient.

possible_combos.append([comb for comb in itertools.combinations_with_replacement(input_list, target_number_of_packages) if np.sum([j[1] for j in comb])==target_number_of_packages])

Disassembled:

possible_combos 

is the output

input_list

is a list of tuples in the form ([...],number_of_packages)

target_number_of_packages

is the number of packages I need to reach. I can combine as many elements of the list "input_list" as I want (repetitions are allowed), but need to reach exactly target_number_of_packages when adding their "number_of_packages", else the combination is not valid.

I was thinking about something like

possible_combos.append([comb for comb in itertools.combinations_with_replacement(input_list, lambda x:x=...)))

but wasn't able to fill the blank.

My question is, is it at all possible to use lambda this way? I don't need an answer for how to deal with this specific usecase because I've solved it differently (with itertools product an a recursive generator function), but I'd still like to know, would there have been a solution?

In short: Is it possible to use lambda to change a value inside another function on the fly?

I've changed the question because I solved the underlying problem differently, but part of it is still something I'd like to know about. As there where no answers, I think an edit is apropriate.



from Can pythons lambda be used to change the inner working of another function?

No comments:

Post a Comment