I want to write this code using a map and/or a filter function. It returns the indices of items in a list provided the sum up to a target
I have used list comprehension for this but can't see how to get the second for loop into the map/filter function. I'm not sure about the syntax to use If I define my own function for the function argument of the map/filter function
num = [2,5,7,11,6,15,3,4]
tgt= 9
[num.index(x) for x in num for y in num if x + y == tgt]
Results:
[0, 1, 2, 4, 6, 7]
Since both filter
and map
work over individual items in a sequence, you would have to view your logic from the perspective of each item in the list, rather than a combination of items, and that means you need to rephrase the expressions used in your list comprehension as functions of individual items. Instead of the filter condition x + y == tgt
, therefore, it is beneficial to view it as x == tgt - y
, where y
also has to be an item in the num
list, so that your list comprehension can be rewritten as:
[num.index(x) for x in num if x in {tgt - y for y in num}]
With this equivalent list comprehension, it then becomes clear that to implement the filter condition would need to make a set by mapping each item in num
to its difference with tgt
, which can be done with the tgt.__sub__
method, and test each item x
in num
if it is a member of the set, which can be done with the set's __contains__
method, and finally, map the filtered sequence to num.index
to output the index of each matching item:
list(map(num.index, filter(set(map(tgt.__sub__, num)).__contains__, num)))
This returns:
[0, 1, 2, 4, 6, 7]