Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
State machine solution in Speedy category for Striped Words by Ch0bits
# migrated from python 2.7
VOWELS = set(list("AEIOUY"))
CONSONANTS = set(list("BCDFGHJKLMNPQRSTVWXZ"))
SEPARATORS = set(list(",.? "))
def checkio(text):
"""
State machine O(n)
"""
words = 0
transitions = 0
state = None
for ch in text.upper() + " ": # add space to force check state at the end of loop
if ch in SEPARATORS:
if state in ['C', 'V'] and transitions > 1:
words += 1
transitions = 0
state = None
continue
if state == 'E':
continue
transitions += 1
# set initial state for a new word
if state is None:
if ch in VOWELS:
state = 'V' # is a vowel
elif ch in CONSONANTS:
state = 'C' # is a consonant
else:
state = 'E'
continue
if state == 'V' and ch in CONSONANTS:
state = 'C'
elif state == 'C' and ch in VOWELS:
state = 'V'
else:
state = 'E' # the word must be ignored
return words
#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
assert checkio("My name is ...") == 3, "All words are striped"
assert checkio("Hello world") == 0, "No one"
assert checkio("A quantity of striped words.") == 1, "Only of"
assert checkio("Dog,cat,mouse,bird.Human.") == 3, "Dog, cat and human"
March 12, 2014
Comments: