How many words from the array A and array B are used in the user input?

Viewed 70

This is a program where I need some help

   A = ["having", "had", "is"]
   B = ["will", "would", "should"]

   sentence = input("Enter a sentence") #E.g. 'I will be having it in the future'

   if A in sentence:
      ...

   elif B in sentence:
      ...

Here I need to know how many words from the array A and array B are used in sentence.

The output here should be:
There is 1 word from A & 1 word from B in the sentence

Can you help me out please?

4 Answers

A reasonably efficient way to do this is to make A, B and the sentence into sets and find the lengths of their intersections. For example:

A = set(["having", "had", "is"])
B = set(["will", "would", "should"])

sentence = 'I will be having it in the future'
S = set(sentence.split())

A_words = A.intersection(S)
B_words = B.intersection(S)

print(f'There is {len(A_words)} word from A and {len(B_words)} word from B in the sentence')

Output:

There is 1 word from A and 1 word from B in the sentence

This should work if you want to count the number present in each list:

A = ["having", "had", "is"]
B = ["will", "would", "should"]

sentence = input("Enter a sentence")
        
        
sentence_split = set(sentence.split())

nbr_words_A = 0
nbr_words_B = 0
for el in sentence_split:
    if el in A:
        nbr_words_A += 1
    if el in B:
        nbr_words_B += 1



print(f"There are {nbr_words_A} words from list A and {nbr_words_B} words from list B in the sentence")

This should work

   A = ["having", "had", "is"]
   B = ["will", "would", "should"]

   sentence = input("Enter a sentence") #E.g. 'I will be having it in the future'
   words_in_sentence = sentence.split()
   # words_in_sentence = np.unique(words_in_sentence) # If you only want unique words
   n_A = len([word for word in words_in_sentence if word in A])
   n_B = len([word for word in words_in_sentence if word in B])

You can follow this it will work. But remember there can be a very short way to do this.

A = ["having", "had", "is"]
B = ["will", "would", "should"]
sentence = input("Enter a sentence:") #E.g. 'I will be having it in the future'
a=0
for i in range(len(A)):
    if A[i] in sentence:
       a=a+1
b=0
for i in range(len(B)):
    if B[i] in sentence:
       b=b+1    
       
print("There is {} word from A & {} word from B in the sentence".format(a,b))

Related