nekodesu
nekodesu

Reputation: 869

Filter( ) function takes function with two inputs

I'm trying to write a filter function that pass me a list of dictionary words that can be formed by letters from a rack.

def test(Rack, word):
"""test whether a string can be formed with the letters in the Rack."""
if word == "" or Rack == []:
    return True
elif word[0] in Rack:
    return True and test(Rack, word[1:])
else:
    return False

Then my map function will need the test function.

def stringsInDic(Rack, dictionary):
    return filter(test(Rack, dictionary) == True, dictionary)

But as we can see, the second input of filter should be an element from the dictionary, which is what filter puts in. So I'm not sure how to write the second argument in test.

Please help!!! Thanks!

Upvotes: 0

Views: 277

Answers (1)

dano
dano

Reputation: 94871

You can use functools.partial:

def stringsInDic(Rack, dictionary):
    func = functools.partial(test, Rack)
    return filter(func, dictionary)

partial allows you to create a sort of place-holder function, which you can add more arguments to later. So func becomes test(Rack, ...). If you were to later call func(something), You'd really be executing test(Rack, something).

Upvotes: 2

Related Questions