Printing the vowels and the vowel count in a string - python

I will have to define a function that takes a person's full name and finds the total number of vowels in that input. And I need to output every vowel including the total
number of vowels found. If the name does not contain any vowel then my function should print
“No vowels in the name!”. Two sample inputs and their corresponding outputs are given below:
Sample input:
(Steve Jobs)
(XYZ)
Sample Output:
Vowels: e, e, o. Total number of vowels: 3
No vowels in the name!
I know it is quite a simple program, but I am facing some difficulties in printing an output as shown in the Sample Output. Here's my incomplete code:
def vowels(full_name):
for i in full_name:
count = 0
if i == 'a' or i == 'A' or i == 'e' or i == 'E' or i == 'i' or i =='I' or i == 'o' or i == 'O' or i == 'u' or i == 'U':
count += 1
print(i, end= ',')
print('Total number of vowels: ', count)
How can I write a clean program to get the expected output? I'm really lost at this point

Some things that may be helpful: As the comments have already pointed out, your long chain of ors can be shortened by using in to check for substring membership:
>>> "a" in "AEIOUaeiou"
True
>>> "b" in "AEIOUaeiou"
False
>>>
You can use filter to create a collection of vowels - only retaining those characters which are vowels:
def is_vowel(char):
return char in "AEIOUaeiou"
vowels = list(filter(is_vowel, "Bill Gates"))
print(vowels)
Output:
['i', 'a', 'e']
>>>
You know that if vowels is empty, you can print "No vowels in the name!". If it's not empty, you can print your other message, and use str.join on vowels to print the vowels, seperated by commas:
print(", ".join(vowels))
Output:
i, a, e
>>>
The number of vowels found is just the length of vowels.

vowels = "aeiou"
def is_vowel(char):
return char in vowels
def count_vowels(word):
vowels = [char for char in word if is_vowel(char.lower())]
return len(vowels)
print('Total number of vowels:', count_vowels("Steve Jobs"))

Related

How do I fix this code so that it doesn't take out vowels that are consecutive of one another?

Hey guys so I'm writing a code for text message abbreviations and these are the following criteria:
Spaces are maintained, and each word is encoded individually. A word is a consecutive string of alphabetic characters.
If the word is composed only of vowels, it is written exactly as in the original message.
If the word has at least one consonant, write only the consonants that do not have another consonant immediately before them. Do not write any vowels.
The letters considered vowels in these rules are 'a', 'e', 'i', 'o' and 'u'. All other letters are considered consonants.
I have written a code and checked it but it is failing for the condition where if the word is composed only of vowels, it is written exactly as in the original message. My code currently is taking out all of the vowels. Like for this example, "aeiou bcdfghjklmnpqrstvwxyz" the code should return "aeiou b"
I tried using another helper function to determine when a word is all vowels but it isn't working. Any suggestions on how to implement something that could make this work? Thanks!
def Vowel(x):
vowels = "a" "e" "i" "o" "u"
value = 0
for ch in x:
if x == vowels:
value = value + 1
return value
def isVowel(phrase):
vowel = "a" "e" "i" "o" "u"
value = 0
for ch in phrase:
if ch in vowel:
value = value + 1
return value
def noVowel(ch):
vowel = "a" "e" "i" "o" "u"
value = 0
for i in ch:
if ch not in vowel:
value = value + 1
return value
def transform(word):
before = 'a'
answer = ""
for ch in word:
if Vowel(ch):
answer += ch
if noVowel(ch) and isVowel(before):
answer += ch
before = ch
return answer
def getMessage(original):
trans = ""
for word in original.split():
trans = trans + " " + transform(word)
trans = trans.strip()
return trans
if __name__ == '__main__':
print(getMessage("aeiou b"))
Your three Vowel-functions are all using a disfunctional for-loop and are highly redundant. Also Vowel() would always return 0, as x may never be a tuple of five vowels.
You would need only one function that just returns True if the character is a vowel and False if it is not. Then, you can use this function in the if-blocks in transform:
def Vowel(x):
vowels = ["a","e","i","o","u"]
return x.lower() in vowels ## True if x is a vowel (upper or lower case)
def transform(word):
before = 'a'
answer = ""
for ch in word:
if Vowel(ch):
answer += ch
if not Vowel(ch) and Vowel(before):
answer += ch
before = ch
return answer
You have not identified what to do with words that have both consonants and vowels...if you provide a few more example inputs and outputs, I might decide to change my code, but this is what I have come up with so far.
I have used regex:
(\b[aeiou]*\b) : finds vowel only words
([bcdfghjklmnpqrstvwxyz]*) : looks for groups of consonants.
The for-loop : helps to return the vowel-only words, or the first letter of the consonant groups.
import re
strings_to_test = ["aeiou bcdfghjklmnpqrstvwxyz ae hjgfd a",
"gg jjjjopppddjk eaf"]
pattern = re.compile(r"(\b[aeiou]*\b)|([bcdfghjklmnpqrstvwxyz]*)")
for line in strings_to_test:
results = []
match_list = pattern.findall(line)
for m in match_list:
if m[0]:
# word of vowels found
results.append(m[0])
elif m[1]:
#consonants found
results.append(m[1][0])
print(results)
OUTPUT:
['aeiou', 'b', 'ae', 'h', 'a']
['g', 'j', 'p', 'f']

Removing ending vowels from a word

This function receives a string as input and should return the number of syllables in the string.
This function has following conditions:
1. Number of syllables is equal to the number of vowels
2. Two or more consecutive vowels count only as one.
3. One or more vowels at the end of the word are not counted.
This is what I've so far but clearly I'm still missing a lot. I'm not sure how to continue here, so I hope you guys can help.
def syllables(word):
vowels = ['a','e','i','o','u','y']
# Delete ending vowel of the word since they don't count in number of syllables
# I've no idea how to remove all ending vowels though
word = word[:-1]
# List with vowels that appear in the word
vowelsList = [x for x in vocals if x in word]
N = []
for i in word:
if i in vowels:
N += i
N = len(N)
return N
print(syllables("bureau"))
# Should print "1" but prints "3" instead
I suggest you the following simple code:
def syllables(word):
vowels = ['a', 'e', 'i', 'o', 'u', 'y']
N = 0
previousLetterIsAVowel = False
# Perform a loop on each letter of the word
for i in word.lower():
if i in vowels:
# Here it is a vowel
# Indicate for the next letter that it is preceded by a vowel
# (Don't count it now as a syllab, because it could belong to a group a vowels ending the word)
previousLetterIsAVowel = True
else:
# Here: it is not a vowel
if previousLetterIsAVowel:
# Here it is preceded by a vowel, so it ends a group a vowels, which is considered as a syllab
N += 1
# Indicate for the next letter that it is not preceded by a vowel
previousLetterIsAVowel = False
return N
print(syllables("bureau")) # it prints 1
print(syllables("papier")) # it prints 2
print(syllables("ordinateur")) # it prints 4
print(syllables("India")) # it prints 1
I also provide a one-line style solution using regex, easily readable too if you know a little bit about regex. It simply counts the number of groups of consecutive vowels that are followed by a consonant:
import re
def syllables(word):
return len(re.findall('[aeiouy]+[bcdfghjklmnpqrstvwxz]', word.lower()))
To check the last vowel you can try something like this (I wouldn't iterate as you're going to loose whole syllables): -> EX: Italian word "Aia" (threshing floor)
if word[-1] in vocals:
word=word[:-1]
-- sorry but I didn't manage to put 'code' into comments so a posted an answer
I would go for:
def syllables(word):
def isVowel(c):
return c.lower() in ['a','e','i','o','u','y']
# Delete ending vowel of the word since they don't count in number of syllables
while word and isVowel(word[-1]):
word = word[:-1]
lastWasVowel = False
counter = 0
for c in word:
isV = isVowel(c)
# skip multiple vowels after another
if lastWasVowel and isV:
continue
if isV:
# found one
counter += 1
lastWasVowel = True
else:
# reset vowel memory
lastWasVowel = False
return counter
Stolen from LaurentH:
print(syllables("bureau")) # prints 1
print(syllables("papier")) # prints 2
print(syllables("ordinateur")) # prints 4
print(syllables("I")) # prints 0
I think we have return 1 if there is previousLetterIsAVowel and N returns 0. Example word Bee.
In Addition to Laurent H. answer
if N == 0 and previousLetterIsAVowel:
return 1
else:
return N

How to write code where you don't define a variable

I am trying to solve this problem below
Assume s is a string of lower case characters. Write a program that
counts up the number of vowels contained in the string s. Valid vowels
are: 'a', 'e', 'i', 'o', and 'u'. For example, if s =
'azcbobobegghakl', your program should print:
Number of vowels: 5
I wrote the following code
s='azcbobobegghakl'
count = 0
for vowels in s:
if vowels in 'aeiou':
count += 1
print ('Number of vowels: ' + str(count))
This was not correct. I learned that you should not define "azcbobobegghakl" as s or g or anything else for that matter. Do I need to use a certain function to accomplish this?
You can use a list comprehension and then count the list.
print("Number of vowels: {}".format(len([vowel for vowel in input() if vowel in "aeiou"])))
The question is asking to count the number of vowels in any string, not just the example azcbobobegghakl, therefore you should replace the fixed string with an input().
What you have seems to do the task required by the question, however, if the do want it in the form of a function you can restate the code you already have as a function:
def count_vowels(s):
count = 0
for vowels in s:
if vowels in 'aeiou':
count += 1
print ('Number of vowels: ' + str(count))
Then, you can execute your program with the following:
count_vowels('azcbobobegghakl')
s = str(input("Enter a phrase: "))
count = 0
for vowel in s:
if vowel in 'aeiou':
count += 1
print("Number of vowels: " + str(count))
This seems to work on python but it is not the right answer.

Most frequent vowel in string python 3

I have created the program for the most frequent vowel in a string but the problem that i am having is i want to print only one letter for the most frequent vowel, not both. My code is displayed below:
from collections import Counter
words = input("Enter a line of text: ")
vowel = "aeiouAEIOU"
x = Counter(c for c in words.upper() if c in vowel)
most = {k: x[k] for k in x if x[k] == max(x.values())}
for i in most:
vowel = i
y = most[i]
print("The most occuring vowel is:",vowel, "with",y,"occurences")
if vowel != words:
print("No vowels found in user input")
When i run the code for example i enter "aa ee" it will print:
The most occuring vowel is: A with 2 occurences
The most occuring vowel is: E with 2 occurrences
I only want it to print either A or E?
Why you don't simply use Counter.most_common() which is most appropriate way for doing this job?
words = input("Enter a line of text: ")
vowels = set("aeiouAEIOU")
x = Counter(c for c in words if c in vowels)
print x.most_common()
Also note that you don't need to use word.upper since you have all the vowels type.And as said in comment you can use set for preserving the vowels which its membership checking complexity is O(1).

In python, how do I find the vowels in a word?

I am trying to make an up language translator. Simple task for me in python. Or so i thought. If you are unaware, up language is when you take a word and say it while adding up before every vowel. for example, Andrew would be Upandrupew. I am trying to find out how find all of the vowels in a user submitted word, and put up before them. Is there a way to cut up a word before all vowels. so excellent would be exc ell ent? thanks.
maybe
VOWELS = 'aeiou'
def up_it(word):
letters = []
for letter in word:
if letter.lower() in VOWELS:
letters.append('Up')
letters.append(letter)
return ''.join(letters)
can be simplified to
def up_it(word):
return ''.join('up'+c if c.lower() in 'aeiou' else c for c in word)
You could do that with a regex:
import re
a = "Hello World."
b = re.sub("(?i)([aeiou])", "up\\1", a)
The (?i) makes it case-insensitive. \\1 refers to the character that was matched inside ([aeiou]).
''.join(['up' + v if v.lower() in 'aeiou' else v for v in phrase])
for vowel in [“a“,“e“,“i“,“o“,“u“]:
Word = Word.replace(vowel,“up“+vowel)
print(Word)
import re
sentence = "whatever"
q = re.sub(r"([aieou])", r"up\1", sentence, flags=re.I)
vowels = ['a', 'e', 'i', 'o', 'u']
def upped_word(word):
output = ''
for character in word:
if character.lower() in vowels:
output += "up"
output += character
return output
Here is a one-liner for the entire problem
>>> "".join(('up' + x if x.upper() in 'AEIOU' else x for x in 'andrew'))
'upandrupew'
Here's one way of doing it.
wordList = list(string.lower())
wordList2 = []
for letter in wordList:
if letter in 'aeiou':
upLetter = "up" + letter
wordList2.append(upLetter)
else:
wordList2.append(letter)
"".join(wordList2)
Create a list of letters (wordList), iterate through those letters and append it to a second list, which is joined at the end.
Returns:
10: 'upandrupew'
In one line:
"".join(list("up"+letter if letter in "aeiou" else letter for letter in list(string.lower())))
I'd probably go with RegExp but there are already many answers using it. My second choice is the map function, witch is better then iterate through every letter.
>>> vowels = 'aeiou'
>>> text = 'this is a test'
>>> ''.join(map(lambda x: 'up%s'%x if x in vowels else x, text))
'thupis upis upa tupest'
>>>
def is_vowel(word):
''' Check if `word` is vowel, returns bool. '''
# Split word in two equals parts
if len(word) % 2 == 0:
parts = [word[0:len(word)/2], word[len(word)/2:]]
else:
parts = [word[0:len(word)/2], word[(len(word)/2)+1:]]
# Check if first part and reverse second part are same.
if parts[0] == parts[1][::-1]:
return True
else:
return False
This is a smart solution which helps you to count and find vowels in input string:
name = input("Name:- ")
counter = []
list(name)
for i in name: #It will check every alphabet in your string
if i in ['a','e','i','o','u']: # Math vowels to your string
print(i," This is a vowel")
counter.append(i) # If he finds vowels then he adds that vowel in empty counter
else:
print(i)
print("\n")
print("Total no of words in your name ")
print(len(name))
print("Total no of vowels in your name ")
print(len(counter))

Categories

Resources