How to get least occurring vowel in string? - python

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.

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

Writing a vowel counter

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

Prompt user until 5 unique vowels or consonants have been input

The purpose of the code is best explained below, for example if I were to enter 'hello' then 'luck' then 'liar' the proper outputs should be '5' 'eouia' 3' and 'ckr'. When I do this however it keeps prompting me for more inputs after entering 'liar'.
###########################################################
# Algorithm
# Ask for a word
# Count and store all vowels in the words (repeats only are
# counted once)
# count and store only consonants after the last vowel, if the
# if last letter is a vowel no consonants are stored
# once all 5 vowels are stored or at least 5 consonants are
# stored
# print
# what vowels appear and how many
# what consonants appear
###########################################################
VOWELS = 'aeiou'
word = input('Input a word: ')
wordlow = word.lower() #converts the input to all lowercase
vowcount = 0
concount = 0
vowcollected_str = ''
concollected_str = ''
#ends the program once 5 vowels or consonants have been stored
while vowcount <= 4 and concount <= 4:
vowcount = 0
concount = 0
#stores the actual letter that is being stored, not just how many
vowcollected_str = ''
concollected_str = ''
for i, ch in enumerate(wordlow):
if ch in VOWELS:
if ch not in vowcollected_str:
vowcollected_str += ch
position = i
vowcount += len(vowcollected_str)
if ch not in VOWELS:
if ch not in concollected_str:
concollected_str += wordlow[i:]
concount += len(word[i:])
word = input('Input a word: ')
wordlow = word.lower()
print(vowcount)
print(vowcollected_str)
print(concount)
print(concollected_str)
I'd keep a set of the all the required vowels and subtract all the letters you input until the set is empty:
VOWELS = 'aeiou'
vowelsSoFar = set(VOWELS)
while vowelsSoFar:
word = input('enter a word: ')
vowelsSoFar -= set(word)
# Feel free to print out the remains vowels, for example
You can use list comprehensions to get the vowels and return the len.
Code
import itertools as it
words = 'hello', 'luck', 'liar'
seen_vowels = "".join(c for w in words for c in w if c in "aeiou")
seen_vowels
# 'eouia'
len(seen_vowels)
# 5
Trailing consonants could be found via takewhile of each reversed word.
trailing_cons = "".join("".join(it.takewhile(lambda x: x not in "aeiou", w[::-1]))[::-1] for w in words)
trailing_cons
# 'ckr'
Details
Note, takewhile grabs all consonants before the first observed vowel. By reversing each word, we get the trailing consonants.
"".join(it.takewhile(lambda x: x not in "aeiou", "luck"[::-1]))
# 'kc'

List slicing issues in python

This code seems like it should work. It sums up the number of words that are "striped" (letter-consonant-letter-etc.) and then returns the sum. However when I test it with print (striped("My name is ...") ) it only counts my and is and gives me a sum of 2 instead of 3... why is name missing?
VOWELS = "AEIOUY"
CONSONANTS = "BCDFGHJKLMNPQRSTVWXZ"
def striped(text):
my_sum = 0
text = text.replace(".", " ").replace(",", " ").split()
vowels = VOWELS.lower()
consonants = CONSONANTS.lower()
for word in text:
word = word.lower()
if ((word[::2] in vowels and word[1::2] in consonants)\
or (word[::2] in consonants and word[1::2] in vowels))\
and len(word) > 1:
print (word)
my_sum += 1
return my_sum
Here is a solution with lists. The problem with your code is that words longer than two characters return a substring when you use [::2] rather than single characters that are tested whether they are contained in vowels / constants.
By converting it to a list first, you can check every item of the list whether it is contained in the according set of characters.
VOWELS = "AEIOUY"
CONSONANTS = "BCDFGHJKLMNPQRSTVWXZ"
def striped(text):
my_sum = 0
text = text.replace(".", " ").replace(",", " ").split()
vowels = VOWELS.lower()
consonants = CONSONANTS.lower()
for word in text:
word = word.lower()
if ((all(c in vowels for c in list(word[::2]))\
and all(c in consonants for c in list(word[1::2])))\
or (all(c in consonants for c in list(word[::2]))\
and all(c in vowels for c in list(word[1::2]))))\
and len(word) > 1:
print (word)
my_sum += 1
return my_sum
print striped("My name is")
You should use set.issubset() instead.
VOWELS = "AEIOUY"
CONSONANTS = "BCDFGHJKLMNPQRSTVWXZ"
def striped(text):
my_sum = 0
text = text.replace(".", " ").replace(",", " ").split()
vowels = set(c for c in VOWELS.lower())
consonants = set(c for c in CONSONANTS.lower())
for word in text:
word = word.lower()
if ((set(word[::2]).issubset(vowels) and set(word[1::2]).issubset(consonants))\
or (set(word[::2]).issubset(consonants) and set(word[1::2]).issubset(vowels)))\
and len(word) > 1:
print (word)
my_sum += 1
return my_sum
striped('My name is...')
The reason it works for my and is is that they are two char words, so you are checking if if m is in the string of constants, and if y is in the string of vowels, which works. For longer words like name, then clearly nm is not in the string of sonsonants, so it fails.
Instead, you should use sets. Essentially, you want to find if set(['n','m']) is a subset of the set of consonants.

Categories