How to find the non repeating words from the strings?

Viewed 114

A word have vowel letters and consonant.

  • There should not be no two vowels together

  • There should not be no two Cosants together

  • "z" is an exception from that rule. z can be repeating together

For example, "man" are True, "king","horse" are False, "zzzz" is True

Code

input_str1 = 'man'
input_str2 = 'king'
input_str3 = 'zzzz'
input_str4 = 'horse'
test_list = [chr(x) for x in range(ord('a'), ord('z') + 1)] 
vowels = ['a','e','i','o','u']

test_list have full alphabets

2 Answers

You may use this regex in python with 2 negative lookaheads:

^(?i)(?!.*[aeiou]{2})(?!.*[^aeiouz]{2})[a-z]+$

RegEx Demo

RegEx Details

  • ^: Start
  • (?i): Enable case ignore matching
  • (?!.*[aeiou]{2}): Negative lookahead to fail the match if we have 2 vowels together
  • (?!.*[^aeiouz]{2}): Negative lookahead to fail the match if we have 2 consonants together
  • [a-z]+: Match 1+ English letters
  • $: End

In Python use:

>>> import re
>>> rx = re.compile(r'^(?!.*[aeiou]{2})(?!.*[^aeiouz]{2})[a-z]+$', re.I)
>>> arr = ['man', 'king', 'horse', 'zzzz']
>>> [s for s in arr if rx.search(s)]
['man', 'zzzz']

No regex solution:

   vowels = ['a','e','i','o','u']
    def check_st(st):
        v, c = 0, 0
        for i in st:
            if i in vowels:
                if v:
                    return False
                v, c = 1, 0
            elif i == 'z':
                continue
            else:
                if c:
                    return False
                v, c = 0, 1
        return True

v is for vowels and c is for consonants

  • If you have v then: v=1 and c=0
  • If you have z then we don't care --> moving to next iteration
  • else it must be c then: v=0 and c=1

Then in next iteration we are ensuring it is not the same kind (v or c)

Just a note:

If 'z' is a 'sequence breaker' then you should assign:

    elif i == 'z':
        v, c = 0, 0
Related