Writing a vowel counter - python

This is my homework assignment:
Write function vowelCount() that takes a string as input and counts
and prints the number of occurrences of vowels in the string.
vowelCount ( ’ Le Tour de France ’ ) a, e, i, o, and u appear,
respectively, 1, 3, 0, 1, 1 times.
This is what I've done so far and it's not working! What do I do?
def vowelCount(sentence):
sentence = sentence.lower()
vowels = "aeiou"
count = 0
if vowels in sentence:
count = +1
print("a, e, i, o, u, appear, respectively," count "times.")
I'm so bad with Python that I can never do my homework on my own. I might as well just give up trying to learn.

You are doing wrong initialization.
vowels = "aeiou"
You should declare it as list or dictionary.
Now the problem with your solution is that you are checking if "vowels" which you have initialized as "aeiou" is present in incoming string or not
if vowels in sentence:
So here you are checking that "aeiou", the whole string is present in the incoming sentence or not. You are not checking for individual vowel and individual character.
The solution will we like iterating all over the sentence from 0 to n-1 where n is its length and check each character.
def count(string):
#we use hashmap to make lookup operation cheap
mp = {'a':1,'e':1,'i':1,'o':1,'u':1}
n = len(s)
count = 0
for i in range(n): #iterating for every element in string
if s[i] in mp: #checking if it is vowel or not
count += 1
return count

Related

How to select certain characters in a string in Python?

My name is Shaun. I am 13 years old and trying to learn python.
I am trying to make a program that finds vowels in an input and then prints how many vowels there are in the input the user gives.
Here is the code:
s = (input('Enter a string: ')) # Let the user give an input (has to be a string)
Vwl = [] # Create an array where we will append the values when the program finds a vowel or several vowels
for i in s: # Create a loop to check for each letter in s
count_a = 0 # Create a variable to count how many vowels in a
count_e = 0 # Create a variable to count how many vowels in e
count_i = 0 # Create a variable to count how many vowels in i
count_o = 0 # Create a variable to count how many vowels in o
count_u = 0 # Create a variable to count how many vowels in u
The function below is pretty long to explain, so summary of the function below is to find a vowel in s (the input) and make one of the counters, if not some or all, increase by 1. For the sake of learning, we append the vowels in the array Vwl. Then, it prints out Vwl and how many letters there are in the list by using len.
if s.find("a" or "A") != -1:
count_a = count_a + 1
Vwl.append('a')
elif s.find("e" or "E") != -1:
count_e = count_e + 1
Vwl.append("e")
elif s.find("i" or "I") != -1:
count_i = count_i + 1
Vwl.append("i")
elif s.find("o" or "O") != -1:
count_o = count_o + 1
Vwl.append("o")
elif s.find("u" or "U") != -1:
count_u = count_u + 1
Vwl.append("u")
print(Vwl)
print(f"How many vowels in the sentence: {len(Vwl)}")
For some odd reason however, my program first finds the first vowel it sees, and converts the whole string into the first vowel it finds. Then it prints down the wrong amount of vowels based on the array of vowels in the array Vwls
Could someone please help me?
The reason your code only prints out the first vowel is because the if statements you coded are not inside a loop, that part of the code runs once and then it finishes, so it only manages to find one vowel.
Here are couple ways you can do what you are trying to do:
Way 1: Here is if you just want to count the vowels:
s = input()
vowel_counter = 0
for letter in s:
if letter in "aeiou":
vowel_counter+=1
print(f"How many vowels in the sentence: {vowel_counter}")
Way 2: Use a python dictionary to keep track of how many of each vowel you have
s = input()
vowel_dict = {}
for letter in s:
if letter in "aeiou":
if letter not in vowel_dict:
vowel_dict[letter]=0
vowel_dict[letter]+=1
print(f"How many vowels in the sentence: {sum(vowel_dict.values())}")
print(vowel_dict)

How to shuffle letters in string with vowel isolated in Python

I am creating a function
Takes input as a string.
Returns a string.
The return string will have the same number of words as the input string, and the same letters as the input string, but the individual words can be of different length. i.e.
perm_lets("try this") == "ist thry"
is a valid return-value. By "number of words" in a string X, we mean the length of the list X.split(' '), i.e. one more than the number of blank spaces in the string. A "word" means a string of letters with no spaces. Lastly,
Every vowel must be isolated, i.e. immediately beside vowels you have at most spaces and/or consonants.
My function can only shuffle the letters of the input string. I would like to know how to isolate the vowel
import random as rd
def perm_lets(input_string):
nS = ''.join(rd.sample(input_string,len(input_string)))
print(nS)
I expect the output of perm_lets("this is a loop") to be something like "si olo pit ahs" but the actual output is " ph siioaos lt" (spaces in the wrong place and vowels are not isolated).
Brute force randomization with disqualifying tests:
import re
import random
import time
def perm_lets(s):
s = list(s)
start = time.perf_counter()
while True:
random.shuffle(s)
p = ''.join(s)
if ' ' in p: continue # no spaces together
if p.startswith(' ') or p.endswith(' '): continue # don't start or end with space
if re.search(r'[aeiou]{2}',p): continue # no vowels together
elapsed = time.perf_counter() - start
return p,elapsed
print(perm_lets('this is a loop'))
print(perm_lets('i bid you adieu'))
Output (4 runs):
('sopihats o i l', 0.0009378000000026532)
('ade udo ibiyi u', 0.07766600000000068)
('i o ha tpsislo', 0.00026450000000011187)
('o adebudu iyi i', 0.00632540000000148)
('o la sstipi ho', 5.2900000000022374e-05)
('udobida eyi i u', 0.3843909999999937) # 1/3 of a second for a tough sentence
('ipa hts o soli', 0.00028810000000589753)
('idida e obu uyi', 0.18083439999999484)
Note: "adieu louie" has no solution.
Here is one way to attempt what you are after. Separates vowels from consonants, shuffles them for randomness, zips vowels and consonants in a poor attempt to isolate the vowels (but this will fail if there are too many more vowels than consonants), randomly selects word length ensuring minimum of one character per word and that the number of output words is the same as the number of input words.
You could probably do a better job isolating vowels by generating more single vowel words when necessary. However, depending on the vowel to consonant ratio and the number of words, there will always be scenarios where you can't both isolate vowels and output the desired number of words.
from itertools import chain, zip_longest
from random import randint, random, shuffle
s = 'this is a loop'
vowels = []
consonants = []
for char in s.replace(' ', ''):
if char in 'aeiouAEIOU':
vowels.append(char)
else:
consonants.append(char)
shuffle(vowels)
shuffle(consonants)
if len(vowels) > len(consonants) or random() > 0.5:
a, b = vowels, consonants
else:
a, b = consonants, vowels
letters = ''.join([c for c in chain.from_iterable(zip_longest(a, b)) if c])
words = []
for i in range(s.count(' '), -1, -1):
x = randint(1, len(letters) - i)
words.append(letters[:x])
letters = letters[x:]
s = ' '.join(words)
print(s)
# EXAMPLE RANDOM OUTPUT:
# si hipa lo tos
you can do it like this also
separate vowels and consonant using regex
combine each vowels to consonant
shuffle the result until result not starts/ends with space and don't have two spaces together
import random
import re
def perm_lets(st):
ls = re.findall(r"([aeiouAEIOU])|(.)", st)
vs, cs = [c for c,_ in ls if len(c)>0], [v for _,v in ls if len(v)>0]
positions = list(range(len(cs)))
result = ""
for v in vs:
if len(positions)==0:
cs.append(" "+v)
else:
p = random.choice(positions)
positions.remove(p)
cs[p//2] += v
while True:
random.shuffle(cs)
result = "".join(cs)
if not (result.startswith(" ") or result.endswith(" ") or " " in result):
break
return result
print(perm_lets("this is a loop"))
print(perm_lets("teis iou")) # more vowels than consonants
Output
tp so hal osii
si u tei o

In this assignment you will ask the user to input an English word, translate that word into ”Pig Latin” and then print both words

I have this assignment due for my computer science class:
In this assignment you will ask the user to input an English word, translate that word into ”Pig Latin” and then print both words.
These are the rules:
If a word starts with a vowel (a, A, e, E, i, I, o, O, u, U) then the translation is formed by adding a "way" to the end of the word. e.g. "at" becomes "atway", "egg" becomes "eggway"
If a word contains no vowels (a, A, e, E, i, I, o, O, u, U) then the translation is formed by a adding a "way" to the end of word. e.g. "my" becomes "myway", "by" becomes "byway"
If a word starts with a consonant and contains a vowel, the translation is formed by moving the consonant(s) up to the first vowel to the end of the word and adding an "ay". e.g. "bat" becomes "atbay", "that" becomes "atthay", "three" becomes "eethray"
Words that start with an initial capital letter should be translated to words with an initial capital letter. e.g. "Houston" becomed "Oustonhay", "Iceland" becomes "Icelandway", "Marry" becomes "Arrymay"
This is the programming I have so far. I am stuck on the 3rd and 4th rule:
def is_vowel(letter):
return letter.upper() in 'AEIOU'
def has_vowel(word):
for letter in word:
if is_vowel(letter):
return True
return False
def translate(word):
if is_vowel(word[0]): #is the first letter
return word + "way"
elif has_vowel(word):
pass
else: #there is no vowel
return word + "way"
#stuff before the loop
print("This program will translate a word from English to Pig Latin.")
choice = "Y"
#stuff in the loop
while choice.upper() == 'Y':
word = input("Please enter a word: ")
print(word, "becomes", translate(word) + ".")
choice = input("Would you like another word? (Y/N) ")
#stuff after the loop
print("Ankthay ouyay!")
I know this is right because we did this part in class but when I came home I was completely lost and unsure what I need to do! Please help!
The third rule requires you to find the index of the first vowel and then flip the characters around. There are several ways to find the index of a first vowel but I reckon this is the one you'll understand the best:
def get_vowel_index(word):
for i, letter in enumerate(word): # use enumerate() to iterate over index, value pairs
if letter.upper() in 'AEIOU':
return i # return the index
Now you can use this function to find the vowel index and then slice the word so it matches your third rule, e.g.:
word = "that"
index = get_vowel_index(word)
pl_word = word[index:] + word[:index] + "ay"
print(pl_word) # atthay
You can even use this function instead of your other functions as it will return None if there are no vowels in the word or the index if there is some so by simple checking the return of this function you can check all three conditions. This gives you a way to optimize your code a bit as the rules are exclusive so you can rewrite your translate() function as:
def translate(word):
vowel_index = get_vowel_index(word) # get the vowel index
# the rule for the vowel as the first letter and no vowels is the same:
if vowel_index == 0 or vowel_index is None:
return word + "way"
# otherwise there is a vowel in the word, flip the consonants to the end:
return word[vowel_index:] + word[:vowel_index] + "ay"
And you can easily test it with:
for v in ("at", "egg", "my", "by", "bat", "that", "three"):
print(translate(v))
Which will produce:
atway
eggway
myway
byway
atbay
atthay
eethray
As for the fourth rule, all you need is to check if the first letter was uppercase in the third condition (as the first two keep the letters unshuffled) and turn it into a titlecase (check str.title()) if it was. So, to complete the translation() function, you can do something like:
def translate(word):
index = get_vowel_index(word) # get the vowel index
if index == 0 or index is None:
return word + "way"
# otherwise there is a vowel in the word, flip the consonants to the end
if word[0].isupper(): # the first letter was uppercase
return (word[index:] + word[:index] + "ay").title() # title-case it!
return word[index:] + word[:index] + "ay"
And to test it:
for v in ("Houston", "Iceland", "Marry"):
print(translate(v))
Yielding:
Oustonhay
Icelandway
Arrymay
As this is a kind of homework assignment, I am not writnig code (a commendable practice on SO).
Rule 3 should consist in finding which character is the first vowel, and then moving the slice of word from beginning up to that character to the end of the word (technically you would replace the string with two slices, as strings are immutable in python) and then append the "ay"
Rule 4: if upper case of the first letter of word (before any modifications) is the same as that letter, then save that info into some variable and based on that change (or not) the first letter of output

Function for counting words of i or more vowels in Python?

In the code below Question 13a asks me to have the function count how many vowels are in a string. (I don't have to call that function in my homework.) But I called it to test it out and that part is completely correct and it works. The string can be both uppercase and lowercase with NO punctuation.
Question 13b asks to create a dictionary. The key is the word in a string (the string has multiple words). The value is how many vowels in that individual word. The question is asking this: If the word has AT LEAST i amount of vowels, then append it to the dictionary (The word with the amount vowels) This function has two parameters. The first one is a string with NO punctuation. The second parameter represents the number of how many vowels the word MUST have to be appended to the dictionary. The professor wants me to call Function 13a this function as part of the algorithm. That being said, the output of Question 13a is the value of the key (the individual word) in this problem. I am having trouble with this question, because I just can't get Python to append the output of 13a (the number of vowels for a word) to the dictionary key.
And also in the code below, I did not work on the part yet where I was supposed use the variable i.
Here is my code:
print("Question 13a")
def vowelCount(s):
vowels = 'aeiou'
countVowels = 0
for letter in s.lower():
if letter in vowels:
countVowels += 1
print(countVowels)
print("Question 13b")
def manyVowels(t, i):
my_string = t.split()
my_dict = {}
for word in my_string:
number = vowelCount(word)
my_dict[word].append(number)
print(my_dict)
print(manyVowels('they are endowed by their creator with certain unalienable rights', 2))
If you cannot understand the question then here is the professor's directions:
Question 13a (10 points)
The letters a, e, i, o and u are vowels. No other letter is a vowel.
Write a function named vowelCount() that takes a string, s, as a parameter and returns the
number of vowels that s contains. The string s may contain both upper and lower case characters.
For example, the function call vowelCount('Amendment') should return the integer 3 because
there are 3 occurrences of the letters 'A' and 'e'.
Question 13b (10 points)
Write a function named manyVowels() that takes a body of text, t, and an integer, i, as
parameters. The text t contains only lower case letters and white space.
manyVowels() should return a dictionary in which the keys are all words in t that contain at least i
vowels. The value corresponding to each key is the number of vowels in it. For full credit,
manyVowels() must call the helper function vowelCount() from Question 11a to determine the
number of vowels in each word. For example, if the input text contains the word "hello", then
"hello" should be a key in the dictionary and its value should be 2 because there are 2 vowels in
"hello".
Input:
1. t, a text consisting of lower case letters and white space
2. i, a threshold number of vowels
Return: a dictionary of key-value pairs in which the keys are the words in t containing at least i
vowels and the value of each key is the number of vowels it contains.
For example, the following would be correct output.
text = 'they are endowed by their creator with certain unalienable rights'
print(manyVowels(text, 3))
{'certain': 3, 'unalienable': 6, 'creator': 3, 'endowed': 3}
Add a condition to add only words with enough vovels
def vowelCount(s):
vowels = 'aeiou'
countVowels = 0
for letter in s.lower():
if letter in vowels:
countVowels += 1
return countVowels
def manyVowels(t, i):
my_string = t.split()
my_dict = {}
for word in my_string:
number = vowelCount(word)
if number >= i:
my_dict[word] = number
return my_dict
The line my_dict[word] = number adds the resuld of vowelCount(word) to your dictionary. But only if the number of vovels is at least i.
def vowelCount(s):
num_vowels=0
for char in s:
if char in "aeiouAEIOU":
num_vowels = num_vowels+1
return num_vowels
def manyVowels(text, i):
words_with_many_vowels = dict()
text_array = text.split()
for word in text_array:
if vowelCount(word) >= i:
words_with_many_vowels[word] = vowelCount(word)
return words_with_many_vowels
print(vowelCount('Amendment'))
text = 'they are endowed by their creator with certain unalienable rights'
print(manyVowels(text, 3))
Output:
3
{'creator': 3, 'certain': 3, 'endowed': 3, 'unalienable': 6}
Try it here!
Your code needs some adjustments:
The first function should return a value not print it:
return (countVowels)
The second function is not adding the key with accompanying value to the dictionary correctly. You should use:
my_dict[word] = number
return {k:v for k, v in my_dict.items() if v > i}

How to get least occurring vowel in string?

I have this code that is supposed to print out the least occurring vowel when a word is entered, but it doesn't print out a vowel and the least value. Here is my code:
#Program to count the least occurring vowels
# take input from the user
w = input("Enter a word or sentence: ")
# string of vowels
vowel = 'aeiouAEIOU'
min_vowel = w[0]
min = w.count(w[0])
# make it suitable for caseless comparisions
w = w.casefold()
count = 0
# count the vowels
for char in w:
if vowel in w:
if w.count(vowel) < min:
min_vowel = w[0]
min = w.count(w)
print ("The least occuring vowel is",min_vowel,"with",min,"occurences.")
Please can anyone tell me where am going wrong?
If you want to be able to identify multiple vowels with the least occurences, I suggest using a different approach:
from collections import Counter
w = input("Enter a word or sentence: ")
vowel = "aeiouy"
# Count occurences of all vowels.
w = Counter(c for c in w.lower() if c in vowel)
# Get vowels with lowest occurences.
min_values = {k: w[k] for k in w if w[k] == min(w.values())}
# Print vowels.
print("The least occuring vowel is:")
for m in min_values:
print("{vowel} with {occ} occurences.".format(vowel=m, occ=min_values[m]))
Example:
>>> (...)
>>> Enter a word or sentence: Bananas are YUMMY!
The least occuring vowel is:
e with 1 occurences.
u with 1 occurences.

Categories