1

I have a list of words . I wants to filter out words which do not have minimum length. I tried filter, but showing some error . My code is

def words_to_integer(x,y):
          return len(x)> y


print("enter the list of words : ")
listofwords =  [ str(x)  for x in input().split()]  #list of words 
minimumlength = print("enter the length ")          
z = list(filter(words_to_integer,(listofwords,minimumlength)))

print("words with length greater than ",minimumlength ,"are" ,z )

error is

 z = list(filter(words_to_integer,(listofwords,minimumlength)))
 TypeError: words_to_integer() missing 1 required positional argument: 'y'

3 Answers 3

2

You should look at functools.partial:

from functools import partial

z = filter(partial(words_to_integer, y=minimumlength), listofwords)

partial(words_to_integer, y=minimumlength) is the same function as words_to_integer, but with argument y being fixed at minimumlength.

Sign up to request clarification or add additional context in comments.

Comments

0

You can't do that. You need to pass a function that already knows about minimumlength.

One easy way to do this would be to use a lambda instead of your standalone function:

filter(lambda x: len(x) > minimumlength, listofwords)

Comments

0

When you type this

list(filter(words_to_integer,(listofwords,minimumlength)))

python tries to do something like this:

z = []
if words_to_integer(listofwords):
    z.append(listofwords)
if words_to_integer(minimumlength):
    z.append(minimumlength)

which will fail, because words_to_integer accepts 2 arguments, but only one was given.

You probably want something like this:

z = []
for word in listofwords:
    if words_to_integer(word):
        z.append(word)

which looks like this with filter:

z = list(filter(lambda word: words_to_integer(word, minimumlength), listofwords))

or use partial like in the other answer.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.