Counting vowels and Consonants in a SubString - python

Having some troubles with finding and counting all possible substrings which begin either with Vowels or Consonants, and print the number of them in the output, some ideas?
word = input()
# defining vowels
vowels = "aeiou"
count_v = 0
count_c = 0
word.lower()
for i in range(len(word)):
for j in range(i, len(word)):
for k in range(i, (j + 1)):
print(word[k], end="")
print()
print(f"number of substrings starting with Vowels: {count_v} - number of substrings starting with Consonants: {count_c} ```

I think the simplest way is to use a list and get its length :
Count_v = len([e for e in words.split(" ") if e[0].lower() in vowels])
I let you do the opposite for consonants.

Use enumerate() to get the letter and index together, rather than using range(len(word)).
You don't need a nested loop, because all the substrings starting at a particular index start with the same letter. And starting at a particular index, there are len(word) - index substrings.
If the letter isn't a vowel, you should check that it's alphabetic to determine if it's a consonant, in case the user enters characters that aren't alphabet.
for i, letter in enumerate(word.lower()):
if letter in vowels:
count_v += len(word) - i
elif letter.isalpha():
count_c += len(word) - i

Related

How to count all substrings in a string, and then sort based on if they begin with a vowel

I tried doing it like this:
# the system waits for the user's string input
word = input()
# defining vowels
vowels = "aeiou"
#// BEGIN_TODO [count_substrings] counting all substrings in a string
count_c: int = 0
count_v: int = 0
total_substrings = (len(word)*(len(word)+1)) // 2
for letter in word:
if letter in vowels:
for i in range(total_substrings):
for j in range(i, total_substrings):
count_v += 1
if letter not in vowels:
for i in range(total_substrings):
for j in range(i, total_substrings):
count_c += 1
print('number of substrings starting with Vowels: {} - number of substrings starting with Consonants: {}'.format(count_v, count_c))
#// END_TODO [count_substrings]
but the code outputs strange numbers. Help would be appreciated on how to approach this problem.
Looks like you're trying to do the same thing twice: You use a formula to calculate the number of substrings, but then you also try to count them with loops. One of those is unnecessary. Or you could combine a little calculation and a little counting like this:
VOWELS = "aeiou"
word = 'test'
n = len(word)
count_v: int = 0
count_c: int = 0
for i, letter in enumerate(word):
# number of substrings starting at i, not counting the empty string:
n_substrings = n - i
if letter in VOWELS:
count_v += n_substrings
else:
count_c += n_substrings
print(f"number of substrings starting with vowels: {count_v}")
print(f"number of substrings starting with consonants: {count_c}")
number of substrings starting with vowels: 3
number of substrings starting with consonants: 7
Note, however, that this approach will overcount if there are identical substrings that can be started at different points in the string. For example, if word = 'eel', the substring 'e' would be counted twice. If you don't want that, it gets more complicated. You could extract all the substrings and collect them in two sets (one for those starting with a vowel, and one for the rest), to remove the duplicates.

How to check if one character is next to another (Flesch index)?

I'm learning to work with strings and my project is to calculate the number of syllables in a sentence.
I'm given some code that calculates the syllables by adding to the variable, syllables += 1, for each vowel. But the end product is wrong because consecutive vowels should only count as a single +1. For example the word "certain" should return two syllables, not three. There is more to it than this but it's not relevant to my question.
Here is how I solved the problem, with an explanation below:
syllables = 0
vowels = "aeiouAEIOU"
vowelContainer = "" # Part of my added code for solution. Create some container to hold
# a representation of consecutive vowels.
for word in text.split():
for vowel in vowels:
syllables += word.count(vowel)
for ending in ['es', 'ed', 'e']:
if word.endswith(ending):
syllables -= 1
if word.endswith('le'):
syllables += 1
for vowel in word: # My added code for solution: rest of lines that follow
if vowel == vowel in vowels: # I fill in the container with Ts and Fs to create a string
vowelContainer += "T" # that I can then check for consecutive vowels.
else:
vowelContainer += "F"
count2ConsecutiveVowels = vowelContainer.count("TT") # I count how many times there are two
count3ConsecutiveVowels = vowelContainer.count("TTT") # or three vowels in the word.
syllables = syllables - count2ConsecutiveVowels - count3ConsecutiveVowels # I subtract the count
vowelContainer = "" # from total syllables
# At the end of the loop I empty the container for the next word.
I managed to come up with a solution, but it is messy. Is there a simpler way to do this?
I think this code should work:
vowels = "aeiouAEIOU"
text = "certain"
syllables_count = 0
if len(text) == 1:
if text[0] in vowels:
syllables_count += 1
else:
for i in range(len(text) - 1):
if text[i] in vowels and text[i+1] not in vowels:
syllables_count += 1
elif text[i] in vowels and i+1 == len(text) - 1:
syllables_count += 1
print(syllables_count)
In order to solve the problem of consecutive vowels you mentioned above, and get the correct number of syllables, I suggest using a regular expression as in the following example:
import re # put in the beginning to import regular expression module
word='certaaaaiin' # just for example
a=re.findall(r'[aeiouAEIOU](?![aeiouAEIOU])',word)
syllables =len(a)
print(syllables)
# output is 2
In this method, any number of consecutive vowels is considered as one in counting
in the regular expression [aeiouAEIOU](?![aeiouAEIOU]), it selects any vowel in the list, in case of that vowel does not have another one after.
vowels = "aeiou"
count = 0
with open("/home/doofinschmurts/PycharmProjects/Practice_001/text.txt", "r") as text:
text = text.read()
for character in range(len(text) - 1):
if text[character] in vowels and text[(character + 1)] not in vowels and text[character - 1] not in vowels:
count += 1
elif text[character] in vowels and text[character + 1] in vowels and text[character - 1] not in vowels:
count += 1
elif text[character] in vowels and text[character + 1] in vowels and text[character + 2] in vowels and text[character - 1] not in vowels:
count += 1
print(count)
I'm new to coding but this script works and the main "jist" is in the long if statements. This wont be the best answer; however, if any veterans wouldn't mind critiquing me also.
Every time you encounter a vowel, you need to increment the syllables counter by 1. Otherwise, you can ignore it.
Try this and see if this meets your needs.
text = input('Enter your word(s) :')
syllables = 0
vowels = "aeiou" #no need to check for upper and lower
for word in text.split():
vowel_found = False #initialize vowel_found to False and check if the world has vowels
for char in word: #iterate thru each char in the word
if not vowel_found and char.lower() in vowels: #for every new vowel found, increment syllables by 1
syllables +=1
vowel_found = True
else:
vowel_found = False #reset to increment counter again
print (syllables)
Here's the output I got:
Enter your word(s) :syllables
2
Enter your word(s) :certain
2
Enter your word(s) :book
1
Enter your word(s) :case
2
Enter your word(s) :Heart
1
Let me know if this code fails. I would like to improve this.

struggling with string characters

I am trying to solve an exercise regarding strings in Python. The exercise says: Write a function that takes a string word and returns a list of strings containing the sound elements of the given word.
A sound element is a maximal sequence of 1 or more consonants followed by 1 or more vowels. In other words, i am supposed to iterate over a string of characters and split it everytime a vowel is followed by a consonant.
Example:
the following string given in input:
S = 'unconditionally'
should return the following list
L = ['u','nco','ndi','tio','na','lly']
In order to solve the exercise, i have written the following function:
def split_words(S):
string = ''
syllables = []
vowels = ['a','e','i','o','u','j','y']
for i in range(len(S)):
if S[i] not in vowels:
string += S[i]
elif S[i] in vowels and S[i+1] not in vowels:
string += S[i]
syllables.append(string)
string = ''
return syllables
Which should be able to solve it. The problem is that i get an index-out-of-range error everytime i run the program. I know the issue is in the elif statement which i don't know how to get rid of.
Is there any way to solve this exercise without importing any external libraries?
Any help will be appreciated
You iterate till the index of the last character :
for i in range(len(S)):
and you have this line:
elif S[i] in vowels and S[i+1] not in vowels:
if i is the last index of S, then it will throw error on S[i+1]
Edit: You can use this:
def split_words(S):
string = ''
syllables = []
vowels = ['a','e','i','o','u','j','y']
for i in range(len(S)):
if S[i] not in vowels:
if len(string) == 0 or not string[-1] in vowels: #here I check if length of string is 0
#in this case I can append letter to it. And also if last letter (`string[-1]`) isn't a vowel,
#then also I can add this letter to string
string += S[i]
else: # if last letter was vowel then we reset string.
syllables.append(string)
string = ''
string += S[i]
else:
string += S[i]
syllables.append(string)
return syllables
We can further simplify code, because we have string += S[i] in every block of if-else:
def split_words(S):
string = ''
syllables = []
vowels = ['a','e','i','o','u','j','y']
for i in range(len(S)):
if S[i] not in vowels and len(string) > 0 and string[-1] in vowels:
syllables.append(string)
string = ''
string += S[i]
syllables.append(string)
return syllables

how to exchange the middle letter and last letter switched?

Ask the user for the input of a word with a minimum of 3 characters. Take that word and exchange the MIDDLE letter with the LAST letter of the word.
If the word is an even number of characters long, take the letter to the right of middle (IE if a word is 6 letters long, you want the 4th character: “switch” is 6 characters and we’d want the ‘t’ as our middle character.
Output to the user their newly rearranged word.
*additional difficulty perform a check that the word is at LEAST 3 letters and display a message that it’s not long enough if something shorter than 3 characters is displayed.strong text
can you guys help me with this?
My code so far:
word=input('Please enter a word with a minimum of 3 characters')
word_length=len(word)
word_middle_index = int(word_length//2)
print('The letter in the middle of the word "'+word+'" is:
word[word_middle_index])
this is how much I've done
this function will complete the task for you:
def switch_mid_and_last(word):
if len(word) < 3:
return("too short word")
else:
mid_letter = len(word)//2
new_word = word[:mid_letter] + word[-1] + word[mid_letter+1:-1] + word[mid_letter]
return(new_word)
the outputs for the next inputs are:
print(switch_mid_and_last("ab"))
>>> too short word
print(switch_mid_and_last("abc"))
>>> acb
print(switch_mid_and_last("abcd"))
>>> abdc
print(switch_mid_and_last("abcde"))
>>> abedc
print(switch_mid_and_last("abcdef"))
>>> abcfed
I've done it so that you can learn how to approach such a problem :
I'd recommend looking into a couple things online :
len function
% operator
[:] operator
For instance :
n % 2 == 0 is True when is even.
"abcd"[1:4] returns "bcd"
word = input("Enter A Word: ")
if len(word) < 3:
print("The word length as to be more than 3 characters")
else:
newWord = ""
middleLetterIndex = 0
lastLetterIndex = len(word) - 1
if len(word) % 2 == 0: # even
middleLetterIndex = int(len(word) / 2) + 1
else:
middleLetterIndex = int(len(word) / 2)
middleLetter = word[middleLetterIndex]
lastLetter = word[lastLetterIndex]
newWord = word[:middleLetterIndex]
newWord += lastLetter
newWord += word[middleLetterIndex+1:lastLetterIndex]
newWord += middleLetter
print(newWord)
Hope this helps you!
For making this easier to grasp, I haven't used any functions, classes, encapsulations or DRY principle here. Since you wanted to show helpful messages in each case, I have also added them.
while True:
word = input("Put a word with at least 3 letters: ")
# check if the word has at least 3 letters
if len(word) < 3:
print("Word needs to be at least 3 letters long!!")
break
# check odd
if not len(word) % 2 == 0:
print("Word length is odd!!!")
# make a list of letters
word_lst = [letter for letter in word]
# mid index
mid_ix = (len(word) - 1) // 2
# last index
last_ix = len(word) - 1
# swap middle and last character
word_lst[mid_ix], word_lst[last_ix] = word_lst[last_ix], word_lst[mid_ix]
# make the list into a string again
word = "".join(word_lst)
print(word)
break
# check even
else:
print("Word length is even!!!")
# make a list of letters
word_lst = [letter for letter in word]
# mid index
mid_ix = (len(word) - 1) // 2 + 1
# last index
last_ix = len(word) - 1
# swap middle and last character
word_lst[mid_ix], word_lst[last_ix] = word_lst[last_ix], word_lst[mid_ix]
# make the list into a string again
word = "".join(word_lst)
print(word)
break

Vowel counter script not executing

vowel = "aeiou"
for i in range(0:len(s)):
if s[i] in vowel == True
count += 1
print("Number of vowels: "+str(count))
The above code doesn't throw any errors in Spyder. I am taking an online course, s is a predefined variable which contains a string. Here I defined s as "big black car"
I have to count the vowels in the string.
When I press enter after typing the code in, I am moved to the next line, nothing happens, I am prompted for more input.
What am I doing wrong?
Working code for you:
s="big black car"
vowel = "aeiou"
count = 0
for i in range(len(s)):
if s[i] in vowel:
count += 1
print("Number of vowels: "+str(count))
Note: First of all, you should use range (len(s)). Second thing is that s[i] in vowel == True will return False. You can easy check it in python console.
>>> 'a' in 'a'
True
>>> 'a' in 'a' == True
False
>>> ('a' in 'a') == True
True
According to my best knowledge Python firstly execute 'a' == True that gives False, then execute 'a' in False. That's why condition is False. Extra parentheses fix that problem.
EDIT: tripleee point that you can use range(len(s)) :).
You need to fix the following:
Get rid of the 0:
Replace the == True with a :
Indent the count += 1 4 spaces to the right
So your code should look as follows:
vowel = "aeiou"
for i in range(len(s)):
if s[i] in vowel:
count += 1
print("Number of vowels: "+str(count))
You can further reduce it to:
vowel = "aeiou"
for i in range(len(s)):
count += s[i] in vowel
print("Number of vowels: "+str(count))
And then further reduce it to:
vowel = "aeiou"
count = sum([s[i] in vowel for i in range(len(s))])
print("Number of vowels: "+str(count))
And then further reduce it to:
vowel = "aeiou"
print("Number of vowels: "+str(sum([s[i] in vowel for i in range(len(s))])))
And then further reduce it to:
vowel = "aeiou"
print("Number of vowels: ", sum([s[i] in vowel for i in range(len(s))]))
And then further reduce it to:
print("Number of vowels: ", sum([s[i] in "aeiou" for i in range(len(s))]))

Categories

Resources