1

If any keyword from an array is mentioned in the title, don't click the title. If the title doesn't mention any of the keywords click the title.

Right now it clicks all the time, and I know why but I don't know how to fix it. It always clicks because it goes through the whole array and eventually there is a keyword that is not in the title. Ideas?

arr = ["bunny", "watch", "book"]

title = ("The book of coding. (e-book) by Seb Tota").lower()
length = len(arr)
for i in range(0,length - 1):
    if arr[i] in title:
        print "dont click"
    else:
        print "click"

This should not click the title because arr[2] is in the title

0

2 Answers 2

1

If you only want it to print or not print for the entire array, you can use any with a comprehension:

if any(word in title for word in arr):
    print("dont click")
else:
    print("click")

In fact the code almost reads like your description of the problem:

If any keyword from an array is mentioned in the title

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

1 Comment

Both your and Bazingaa code got it working, this is much simples though.
0

Using index variables when you don't need them is unpythonic. There's no need for range here. (By the way, the stop argument is the first number you don't want, just like a list slice.)

arr = ["bunny", "watch", "book"]

title = ("The book of coding. (e-book) by Seb Tota").lower()
for s in arr:
    if s in title:
        print "dont click"
        break
else:
    print "click"

Python allows an else clause in for loops for when you're searching for the first answer, but still need a default when you don't break the loop. But this find-first pattern is something you can actually do in one line.

print next(("dont click" for s in arr if s in title), "click")

3 Comments

This will still print click twice and dont click once. The OP wants only dont click if either word is present
@Bazingaa the indentation is correct. Loops can have an else clause in Python. Try running it yourself.
I just realized that your and my code will print dont click even if we replace the word book by boo or by bo or by just b. That's what in does. The OP wants to see if the words are existing as a whole. But I assume the OP will not have incomplete words

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.