Home > Net >  Analise string see if vowels and 2 consecutive letters
Analise string see if vowels and 2 consecutive letters

Time:10-31

how can i analise a string one by on, then see if it has 2 vowels (non-capital), and see if it as at least two consecutive letters of the alphabet (non-capital as well)

e.g.: aabcd is valid cdefgh not valid

CodePudding user response:

We'll iterate the string one by one. We'll create a list which contains all the alphabets. Then when we iterate the string, we'll check every element with all the alphabets. The moment we get the correct alphabets we'll check whether the next letter of the string is the next consecutive alphabet or not. If yes, then we'll convert f to True and break the loop. For vowels, we'll take a variable count. Count all the vowels in the string using loop. After all these steps, we'll check whether f is True and count is >2. If yes, it is valid. Else, invalid. Your code:

x=input("Enter string: ")
f=False
alphas="abcdefghijklmnopqrstuvwxyz"
vowels="aeiou"
for i in range(len(x)):
    for j in range(len(alphas)):
        if (j 1)<len(alphas) and (i 1)<len(x):
            if x[i]==alphas[j] and x[i 1]==alphas[j 1]:
                f=True
        
count=0
for i in x:
    if i in vowels:
        count =1

if f==True and count>=2:
    print("valid")
else:
    print("invalid")

CodePudding user response:

Quick solution:

1st line of function: Defining vowels.
2nd: We will use num from the length of our string to slice the string.
3rd: Checking that slice len > 1, this will prevent index errors on odd length strings.
4th: Using all() to check that both characters of our slice are in vowels, if they are then return True.
5th: After exiting the for loop we will return false because our previous if statement did not return True.

def string_analyze(string: str) -> bool:
    vowels = 'aeiou'
    for num in range(len(string)):
        if len(string[num:num 2]) > 1:
            if all(i in vowels for i in string[num:num 2]):
                return True
    return False
  • Related