0

I've got two lists of words. I want to check if the first word from listA is in listB, then second word from listA is in listB, and so on. If a word is present, I increment some integer variable. I have to do it with recursive function isWordInArray which takes 2 arguments: listA and listB

I've tried to do something like this,but I have no idea if it's correct :

isWordInArray(listA, listB) = isWordInArray(listA[i] in listB)
4
  • 4
    Is this an assignment ?. Even if it so can you care to show what you have done. With sample input and output ?. Commented Feb 25, 2016 at 7:07
  • It's just a formula. For example input listA=["dog","is","black"] listB=["my","cat","is","white"] output 1 My recursive function should return 1,because only "is" appears in both lists.What I haven't mentioned is that I will remove that word from both lists. Commented Feb 25, 2016 at 7:24
  • Do you need a recursive function or normal funtion would do ?. Commented Feb 25, 2016 at 7:26
  • I need a recursive function Commented Feb 25, 2016 at 7:37

1 Answer 1

1

Edited after I saw your comment clarifying what you are trying to do.

Maybe something like:

index = 0

def isWordInArray(listA, listB):
    global index
    if index < len(listA):
        if listA[index] in listB:
            item_to_remove = listA[index]
            listA.remove(item_to_remove)
            listB.remove(item_to_remove)
            print "Removed {}".format(item_to_remove)
        else:
            index += 1

        isWordInArray(listA, listB)
Sign up to request clarification or add additional context in comments.

7 Comments

I think there is a little misunderstanding.I just want to check if the current value is in listB.For example,let's say input is listA=["i","have","a","white","cat"] listB=["this","cat","is","white"] Output 2 I check the first word from listA with every word from listB,if they are same,I increment variable and I also remove words from both lists.If it should be done "normal way",it would be: for i in listA: if i in listB: num+=1 listB.remove(i) listA.remove(i)
I edited my answer above. Hopefully that's more what you are looking for.
I think you forgot to return isWordInArray(listA, listB) .But compiler returns error because of index.I think it should be global variable,or am I wrong?
Right. I'm always thinking in terms of class definitions. Edited.
There's no need to return any results in this case, however, because Python passes the parameters by reference. So modifications to the array in the function affect the array reference. So if you add a print after executing the function you'll see your original arrays have been modified.
|

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.