Home > Mobile >  Counting Consecutive Words Within a String
Counting Consecutive Words Within a String

Time:12-12

i am given string and supposed to count three consecutive words

so "Hello hello hello" is True, "Hello hello 123 hello" is False, and "Hello 123 hello hello hello" is True

i cannot find way to reset my counter when number showing up. in second example i return true because of this i using is alpha by the way and am using python. can anyone help with counting the words the right way

counter = 0
    for word in words:
        if word.isalpha():
            counter  = 1

CodePudding user response:

You may use re.search here:

inp = ["Hello hello hello", "Hello hello 123 hello", "Hello 123 hello hello hello"]
for x in inp:
    if re.search(r'\b(\w ) \1 \1\b', x, flags=re.I):
        print("MATCH: "   x)
    else:
        print("NO MATCH: "   x)

This prints:

MATCH: Hello hello hello
NO MATCH: Hello hello 123 hello
MATCH: Hello 123 hello hello hello

CodePudding user response:

also you can try this solution out...

succ = 0
for word in words.split():
    succ = (succ   1)*word.isalpha()
    if succ == 3: return True
else: return False

CodePudding user response:

you can try using TWO solutions:

  1. use a flag

    • this would entail using a boolean before your loop and switching the bool value should you encounter a negation, or a number in this case
  2. reset your counter using isnum()

    • this would be the easiest and simpler solution for you as you would only need to add an if statement to your code, reverting your counter should a number be found

for more information follow this link What is a flag in python while loops? or this one https://www.tutorialspoint.com/python/string_isnumeric.htm

  • Related