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.
Related
Probelm Description:
sms_encoding() which accepts a sentence and converts it into an abbreviated sentence to be sent as SMS and returns the abbreviated sentence.
Rules are as follows:
a. Spaces are to be retained as is
b. Each word should be encoded separately
If a word has only vowels then retain the word as is
If a word has a consonant (at least 1) then retain only those consonants
My Code:
#PF-Assgn-50
def sms_encoding(data):
#start writing your code here
vowels=set("aeiouAEIOU")
v_list=[]
c_list=[]
final_list=[]
new_string=''
word=data.split()
word2=[]
for i in range(0,len(word)):
ch=word[i]
#print(ch)
if ch in vowels:
v_list.append(ch)
for letter in word[i]:
if letter not in vowels:
c_list.append(letter)
c_list.append(" ")
new_string=''.join(v_list)+''.join(c_list)
final_list.append(new_string)
#print(v_list)
return ' '.join(final_list)
data="Have a Nice Day"
print(sms_encoding(data))
My Output:
aHv **<2spaces>** Nc **<1space>** Dy
Expected Output:
Hv a Nc Dy (contains only 1 space)
You could iterate over words in the sentence taking only consonants only if the word contains atleast one consonant:
data = "Have a Nice Day"
splitted = data.split()
for i, x in enumerate(splitted):
if not all(y in 'aeiou' for y in x.lower()):
splitted[i] = ''.join([y for y in x if y.lower() not in 'aeiou'])
print(' '.join(splitted))
# Hv a Nc Dy
This will work for all cases... retains all except vowels when even 1 character in a string is not vowel.
def sms_encoding(data):
vowels = set("aeiouAEIOU")
words = data.split()
encoded_words = []
for i in range(0,len(words)):
vow_count = 0
cons_word = []
for x in words[i]:
if x in vowels:
vow_count =vow_count+1
elif x not in vowels:
cons_word.append(x)
if vow_count == len(words[i]):
encoded_words.append(words[i])
elif vow_count != len(words[i]):
encoded_words.append("".join(cons_word))
encoded_msg = " ".join(encoded_words)
return encoded_msg
data=input("Kindly enter your message for sms encoding : ")
print(sms_encoding(data))
Try and let me know!
def sms_encoding(data):
vowel = "aeiouAEIOU"
list1 = data.split()
list2 = []
for i in list1:
length=len(i)
if length == 1:
list2.append(i)
list2.append(" ")#to add spaces between the words
else:
count=0
for a in i:
if a in vowel:
count+=1
if count==length: #to check if all the letters are vowels
list2.append(i)
list2.append(" ")
for a in i:
if a not in vowel:
list2.append(a)
list2.append(" ")
list2.pop() #to remove the extra space at the end of the whole sentence
q="".join(list2)
return q
data = "I love Python aeio"
print(sms_encoding(data))
try this code it will work the question is from infytq
def sms_encoding(data):
data=data.lower()
a=data.split()
v1=""
for i in range(0,len(a)):
z=a[i]
v=""
c1=0
for j in z:
if j not in ('a','e','i','o','u'):
v=v+j
elif j in ('a','e','i','o','u'):
c1=c1+1
if(c1!=len(z)):
v1=v1+v+" "
elif(c1==len(z)):
v1=v1+z+" "
word=v1[0:len(v1)-1]
return word
data="I love Python"
print(sms_encoding(data))
def sms_encoding(new_s):
encrypt_string = []
consonant_list = []
vowel_set = set("aeiouAEIOU")
for word in range(0, len(new_s)):
v_letter = new_s[word]
if v_letter in vowel_set:
encrypt_string.append(v_letter)
for letter in v_letter:
if letter not in vowel_set:
consonant = " ".join(letter)
encrypt_string.append(consonant)
encrypt_string.append(" ")
encrypt_string = "".join(encrypt_string)
print(encrypt_string)
s = input("Enter a string ")
new_s = s.split()
sms_encoding(new_s)
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'
I am trying to write a program that counts vowels and consonants in Python, then print the number of vowels and consonants in two statements. The vowels and consonants have to be in two different functions. I have most of it complete but I cannot figure out two errors.
1.) How to stop my script from printing a new line for each count of the vowels. I have tried numerous variations of accumulators and print statements but none seem to work.
2.) I cannot get my countConsonants function to run at all. I am assuming I would have similar problems to number one but I cannot get it to even run. I am assuming it has to do with the way I am calling the function from the main function but I am not sure.
Here is what I have:
def main():
user_input = input("Enter a string of vowels and consonants: ")
vowel_list = set(['a','e','i','o','u'])
countVowels(user_input, vowel_list)
countConsonants(user_input, vowel_list)
def countVowels(user_input, vowel_list):
user_input.lower()
index = 0
vowels = 0
while index < len(user_input):
if user_input[index] in vowel_list:
vowels += 1
index += 1
print ('Your input has', vowels , 'vowels.')
def countConsonants(user_input, vowel_list):
user_input.lower()
index = 0
consonants = 0
while index < len(user_input):
if user_input[index] not in vowel_list:
consonants += 1
index += 1
print ('Your input has' , consonants , 'consonants.')
main()
Here is an IO:
Enter a string of vowels and consonants: aaeioulkjj
Your input has 1 vowels.
Your input has 2 vowels.
Your input has 3 vowels.
Your input has 4 vowels.
Your input has 5 vowels.
Your input has 6 vowels.
Indentation is key.
The print should only happen after the while loop is done, so it must be indented the same as the while. The increment of the index is in the wrong spot as well: this must happen each time regardless of whether or not the if condition evaluates to True. (With your alignment, the index only increases past vowels and may never get far enough to allow the while loop to end; this is why you never got to countConsonants.)
Your countVowels function then becomes:
def countVowels(user_input, vowel_list):
index = 0
vowels = 0
while index < len(user_input):
if user_input[index] in vowel_list:
vowels += 1
index += 1
print ('Your input has', vowels , 'vowels.')
By the way, consider using a for loop here over the characters in user_input instead of while and indexing; i.e. use something like:
for char in user_input:
if char in vowel_list:
vowels += 1
I read through your code and found a couple issues. You seem to not be calling .lower in the right spot. It doesn't modify the string, it simply returns a lowercase version of the string. And i combined your vowels and consonants with a little math. Additionally, I added a conditional for loop that will scan through the letters and pick all the vowels out, then it will take the length of the vowel list found. Finally, I also just combined vowel_list into a string to make it look prettier.
def main():
user_input = input("Enter a string of vowels and consonants: ").lower()
vowel_list = 'aeiou'
countVowelsAndConsoants(user_input, vowel_list)
def countVowelsAndConsoants(user_input, vowel_list):
vowels = len([char for char in user_input if char in vowel_list])
print ('Your input has', vowels , 'vowels.')
print ('Your input has', len(user_input)-vowels, 'consonants.')
main()
If you need them both separate:
def main():
user_input = input("Enter a string of vowels and consonants: ").lower()
vowel_list = 'aeiou'
countVowels(user_input, vowel_list)
countConsonants(user_input, vowel_list)
def countVowels(user_input, vowel_list):
vowels = len([char for char in user_input if char in vowel_list])
print ('Your input has', vowels , 'vowels.')
def countConsonants(user_input, vowel_list):
vowels = len([char for char in user_input if char in vowel_list])
print ('Your input has', len(user_input)-vowels, 'consonants.')
main()
##it is list
listChar = ['$','a','8','!','9','i','a','y','u','g','q','l','f','b','t']
c = 0##for count total no of elements in a list
cVowel = 0 # for count vowel
cConst = 0 # for count consonants
cOther = 0 # for count other than consonants and vowels
for i in listChar : ## use loop for count eaxh elements
c += 1
if i in 'aeiou' : ## check it is vowewl
cVowel = cVowel + 1 # count vowel
elif i in '!##$%^&*()+-*/123456789~`' : # other than alphabets
cOther = cOther + 1 # count other than alphabets elements
else :
cConst = cConst + 1 ## count consonants if above contion not satisfied
print all results
print ("total number of element in the list : ", c)
print("count vowels characters : ",cVowel)
print("count consonants characters : ",cConst)
print("count other characters : ",cOther)
I hope this is what you want. I replaced the while loop with the for loop and added a variable count_Consonant with a list of consonants.
def countVowels(user_input, vowel_list):
vowels = 0
for i in vowel_list:
if i in user_input:
vowels+=1
print ('Your input has {} vowels.'.format(vowels))
def countConsonants(user_input, count_Consonants):
consonants = 0
for i in count_Consonants:
if i in user_input:
consonants+=1
print ('Your input has {} consonants.'.format(consonants))
def main():
user_input = input("Enter a string of vowels and consonants: ").lower()
vowel_list = set(['a','e','i','o','u'])
countVowels(user_input, vowel_list)
count_Consonants = set(["b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z"])
countConsonants(user_input, count_Consonants)
main()
def VowCons(Str):
Vcount = 0
ConsCount = 0
Vowels = ['a','e','i','o','u']
for char in Str:
if char in Vowels:
Vcount +=1
else:
ConsCount +=1
print(Vcount," is the number of vowels and ",ConsCount," is the count of consonants")
VowCons("how many vowels and consonants are there")
Define a procedure is_vowel.
It takes your name as its input and prints:
‘Your name starts with avowel’
if it starts with a vowel, and prints ‘Your name starts with a consonant’, otherwise?
Example:
is_vowel(‘Ali’) ‘Your name starts with a vowel’
is_vowel(‘aqsa’) ‘Your name starts with a vowel’
is_vowel(‘Sam’) ‘Your name starts with a consonant’
Here is a program that counts vowels and consonants.
It makes use of a dictionary slice:
itemgetter(*vowel_or_consonant)(c) # slice
Script:
from collections import Counter
from operator import itemgetter
from string import ascii_letters
VOW = set('aeiouAEIOU')
CON = set(ascii_letters)-VOW
def letter_count(s, vowel_or_consonant):
c = Counter(s)
return sum(itemgetter(*vowel_or_consonant)(c))
s ="What a wonderful day to program"
print('Vowel count =', letter_count(s, VOW))
print('Consonant count =', letter_count(s, CON))
"""
================= RESTART: C:/Old_Data/python/vowel_counter.py =================
Vowel count = 9
Consonant count = 17
"""
I'm a beginner learning the python language and I'm stumped on how take the vowels of a word and replacing them with an underscore.
So far this is what I have come up with and it just doesn't work
word = input("Enter a word: ")
new_word = ""
vowels = "aeiouy"
for letter in word:
if letter != vowels:
new_word += word
else:
new_word += "_"
print(new_word)
You can use string.translate and maketrans.
from string import maketrans
vowels = "aeiouy"
t = "______"
st = "trying this string"
tran = maketrans(vowels, t)
print st.translate(tran)
# Gives tr__ng th_s str_ng
You may also want to check uppercases.
you can use regex
import re
print(re.sub("[aeiouAEIOU]", "_", "abc")) # prints _bc
Make vowels an array with each element it's own letter.
Then do
for letter in word:
if letter in vowels:
letter = "_"
Lists can be used to easily build words, and with .join() you can combine the list items into a single string.
word = 'pizza'
vowels = "aeiouy"
new_word = []
for letter in word:
if letter in vowels:
new_word.append('_')
else:
new_word.append(letter)
print(''.join(new_word))
Here's the same thing in a generator expression:
word = 'pizza'
vowels = "aeiouy"
new_word = ''.join(c if c not in vowels else '_' for c in word)
print(new_word)
To answer why your approach didn't work.
if letter != vowels:
Does not do what you are thinking. It actually compares the letter against a full string "aeiouy". It will always be unequal (e.g. "a" != "aeiouy" is True and so is any other letter).
More likely what you mean was
if letter in vowels:
Which under the hood will iterate over vowels and compare each character to letter, returning True if any of the letters match.
The second mistake is here
new_word += word
You are adding the original word to the new word rather than the letter you just checked. So make that
new_word += letter
The third thing to note is that your logic is the reverse of what you intended. You wanted to replace vowels with _ but your if statement allows vowels into the new word and replaces consonants with the underscore. So if you reverse your if and else clauses.
All up you end up with
word = input("Enter a word: ")
new_word = ""
vowels = "aeiouy"
for letter in word:
if letter in vowels:
new_word += '_'
else:
new_word += letter
print(new_word)
Using a list comprehension and setting vowels as a set object (this is really only valuable for speeding up performance if you have a large list of words over which you're iterating):
>>> vowels = set("aeiouy")
>>> word = 'ampersand'
>>> new_word = "".join([letter if letter not in vowels else "_" for letter in word])
>>> print(new_word)
_mp_rs_nd
If you have Python 3, use str.maketrans to build a string translation table:
vowels = "aeiouy"
vowels += vowels.upper()
tr = str.maketrans(vowels, '_' * len(vowels))
print('Yo, this is a wacky phrase!'.translate(tr))
Shows: __, th_s _s _ w_ck_ phr_s_!
DRAX: I'll do you even better!
def replace_vowels(word):
vowels = ['a', 'e', 'i', 'o', 'u']
for x in (word.lower()):
if x in vowels:
word = word.replace(x, "_")
print(word)
replace_vowels('Stackoverflow')
Output
St_ck_v_rfl_w
I am trying to take an input string and replace any vowels in it with a whitespace. How do you do this?
def w_space (s):
vowels = "aeiouAEIOU"
string = s
for a in string:
for b in vowels:
if string[a] == vowels[b]:
vowels = ""
return string
First of all instead of setting string = s simply loop through s as it is. Also, instead of looping through both s and vowels just loop s and check if the letter is in vowels, if so add a white space to string if not add the letter to string. Here is the code:
def w_space (s):
vowels = "aeiouAEIOU"
string = ""
for a in s:
if a in vowels:
string += " "
else:
string += a
return string
def f(s):
l = list(s)
for i in range(len(l)):
if l[i] in "aeiouAEIOU":
l[i] = " "
return ''.join(l)
This can be accomplished with a list comprehension
def w_space(s):
vowels = "aeiouAEIOU"
return "".join([" " if x in vowels else x for x in s])
Regex is an option as well
def w_space (s):
from re import sub, IGNORECASE
vowels = r'[aeiou]'
return sub(vowels, ' ', s, flags=IGNORECASE)