dimanche 24 novembre 2019

Checking if either of 2 words exist and getting their index in a list when only one of them can exist in the list in python 3

So I'm trying to search a sentence (converted to a list using split() method) for similar words and compare it to the index of another word (or one among 2 words).

For example, the sentence can be "Is the light on?" or "Are the lights on?" I want to check if either "light" and "on" exists in the sentence or "lights" and "on" exists in the sentence, when both "light" and "lights" cannot together exist in the sentence (or list) and that they appear after "is" or "are". If that's true, it should execute some code else if the sentence is "The lights are on." or "The light is on.", it should execute some other code.

I have tried the following code but throws an exception.

sentence = "is the light on?"
query = sentence.split()
if (query.index('is')<query.index('light') and query.index('is')<query.index('on')) or (query.index('are')<query.index('lights') and query.index('are')<query.index('on')):
    #some code
else:
    #some other code

There are a few more condition checks like this and splitting all of them seemed redundant so I don't know what to do. I could split it to 2 ifs and put the same code again. In any case, ValueError exception will be thrown, and I'm not sure how to handle it correctly.

Can you please guide me?

Aucun commentaire:

Enregistrer un commentaire