Count vowels and print duplicate vowels - python

I have a code that counts the number of vowels from the user input and prints them. Furthermore, what I also want to do is to print out the duplicate vowels.
The first part of the code runs fine and it does print out the number of vowels in whatever the user gives input but the second part does not seem to work. I am attaching the code I have come up with.
user_name = input('Please enter your name: ')
count = 0
for vowels in user_name:
if vowels.lower() == "a" or vowels.lower() == "e" or vowels.lower() == "i" or vowels.lower() == "o" \
or vowels.lower() == "u":
count = count + 1
print(f'Number of vowels are {count}')
dupes = ""
for rep_vows in user_name:
if rep_vows not in dupes:
# dupes.append(rep_vows)
print(dupes)

If you want to get the duplicates, you should be checking if a new vowel was already added to the list (or string) of vowels found.
A simple modification will get you this
duples = ''
for rep_vows in user_name:
if rep_vows in duples:
print(rep_vows)
if rep_vows.lower() in "aeiou":
duples += rep_vows
Since you know how to use in, you can change the first part to:
for vowels in user_name:
if vowels.lower() in "aeiou":
count = count + 1

For counting things Python has Counter dict here is some examples:
>>> from collections import Counter
>>> import re
>>> # Count vowels
>>> Counter(re.findall('[aieouAEIOU]', 'Daniel Hilst'))
Counter({'i': 2, 'a': 1, 'e': 1})
>>> # Summing up
>>> sum(Counter(re.findall('[aieouAEIOU]', 'Daniel Hilst')).values())
4
>>> # Count words
>>> Counter(re.findall(r'\w+', 'some text'))
Counter({'some': 1, 'text': 1})
>>>
You can find the documentation at collections package docs: https://docs.python.org/3.7/library/collections.html

I think a native Python Counter is really what you should try to use here. It is just a glorified dictionary but it really trims down the amount of code you need to write to achieve your goal.
from collections import Counter #import Counter from Python's collections standard library
user_name = input('Please enter your name: ')
vowels = ['a','e','i','o','u'] # create a list of your vowels
counter = Counter() # initialize counter
for letter in user_name:
if letter in vowels:
print(letter)
counter[letter]+=1
print(counter)

Your solution is ok, but dupes should be a list (of repeated vowels), and you can use another list for the already seen vowels; so when you see a vowel, you check if that one is already in "seen". If the vowel is in seen, you append it to dupes, otherwise, you append it to seen, so when that one repeats, it will be appended to dupes.
And finally, you print the list of dupes.
user_name = input('Please enter your name: ')
count = 0
for vowels in user_name:
if vowels.lower() == "a" or vowels.lower() == "e" or vowels.lower() == "i" or vowels.lower() == "o" or vowels.lower() == "u":
count = count + 1
print(f'Number of vowels are {count}')
seen = []
dupes = []
for rep_vows in user_name:
if rep_vows not in seen:
seen.append(rep_vows)
else:
dupes.append(rep_vows)
print(dupes)

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)

Counting number of occurrences in a string

I need to return a dictionary that counts the number of times each letter in a predetermined list occurs. The problem is that I need to count both Upper and Lower case letters as the same, so I can't use .lower or .upper.
So, for example, "This is a Python string" should return {'t':3} if "t" is the letter being searched for.
Here is what I have so far...
def countLetters(fullText, letters):
countDict = {i:0 for i in letters}
lowerString = fullText.lower()
for i in lowerString:
if i in letters:
countDict[i] += 1
return countDict
Where 'letters' is the condition and fullText is the string I am searching.
The obvious issue here is that if the test is "T" rather than "t", my code won't return anything Sorry for any errors in my terminology, I am pretty new to this. Any help would be much appreciated!
To ignore capitalization, you need to input =
input = input.lower ()
.Lists all characters of the input text using list operations.
It can also be used as a word counter if you scan the space character.
input = "Batuq batuq BatuQ" # Reads all inputs up to the EOF character
input = input.replace('-',' ')#Replace (-, + .etc) expressions with a space character.
input = input.replace('.','')
input = input.replace(',','')
input = input.replace("`",'')
input = input.replace("'",'')
#input= input.split(' ') #if you use it, it will sort by the most repetitive words
dictionary = dict()
count = 0
for word in input:
dictionary[word] = input.count(word)
print(dictionary)
#Writes the 5 most repetitive characters
for k in sorted(dictionary,key=dictionary.get,reverse=True)[:5]:
print(k,dictionary[k])
Would something like this work that handles both case sensitive letter counts and non case sensitive counts?
from typing import List
def count_letters(
input_str: str,
letters: List[str],
count_case_sensitive: bool=True
):
"""
count_letters consumes a list of letters and an input string
and returns a dictionary of counts by letter.
"""
if count_case_sensitive is False:
input_str = input_str.lower()
letters = list(set(map(lambda x: x.lower(), letters)))
# dict comprehension - build your dict in one line
# Tutorial on dict comprehensions: https://www.datacamp.com/community/tutorials/python-dictionary-comprehension
counts = {letter: input_str.count(letter) for letter in letters}
return counts
# define function inputs
letters = ['t', 'a', 'z', 'T']
string = 'this is an example with sTrings and zebras and Zoos'
# case sensitive
count_letters(
string,
letters,
count_case_sensitive=True
)
# {'t': 2, 'a': 5, 'z': 1, 'T': 1}
# not case sensitive
count_letters(
string,
letters,
count_case_sensitive=False
)
# {'a': 5, 'z': 2, 't': 3} # notice input T is now just t in dictionary of counts
Try it - like this:
def count_letters(fullText, letters):
countDict = {i: 0 for i in letters}
lowerString = fullText.lower()
for i in lowerString:
if i in letters:
countDict[i] += 1
return countDict
test = "This is a Python string."
print(count_letters(test, 't')) #Output: 3
You're looping over the wrong string. You need to loop over lowerString, not fullString, so you ignore the case when counting.
It's also more efficient to do if i in countDict than if i in letter.
def countLetters(fullText, letters):
countDict = {i.lower():0 for i in letters}
lowerString = fullText.lower()
for i in lowerString:
if i in countDict:
countDict[i] += 1
return countDict
What you can do is simply duplicate the dict with both upper and lowercase like so:
def countLetters(fullText, letters):
countDict = {}
for i in letters:
countDict[i.upper()]=0
countDict[i.lower()]=0
lowerString = fullText.lower()
letters = letters.lower()
for i in lowerString:
if i in letters:
countDict[i] += 1
if (i!=i.upper()):
countDict[i.upper()] +=1
return countDict
print(countLetters("This is a Python string", "TxZY"))
Now some things you can also do is loop over the original string and change countDict[i] += 1 to countDict[i.lower()] +=1
Use the Counter from the collections module
from collections import Counter
input = "Batuq batuq BatuQ"
bow=input.split(' ')
results=Counter(bow)
print(results)
output:
Counter({'Batuq': 1, 'batuq': 1, 'BatuQ': 1})

How to iterate through a list using a stepper variable in Python?

I am trying to write a function that returns a hangman style output given an input of guessed characters and a secret to be guessed. I start by making a new list aset to - as many times as the length of the secret. I then iterate through this variable and test if a[stepper] == letter where letter is the walker as we loop through.
Currently to keep track of this stepper I am using this code
a = ["-"] * len(secret)
for curr in guessed:
letter_count = 0 # Stepper
for letter in secret:
if curr == letter:
a[letter_count] = curr
letter_count += 1
Is there a built in functionality for letter_count as I am using here?
Use enumerate() builtin function like this:
a = ['-'] * len(secret)
for curr in guessed:
for i, letter in enumerate(secret):
if curr == letter:
a[i] = curr
You could create the displayed word dynamically with join and a comprehension. The guesses are stored in a set and a ternary operator checks if the letter or - should be displayed:
>>> word = "hangman"
>>> guessed = set()
>>> ''.join(letter if letter in guessed else '-' for letter in word)
'-------'
>>> guessed.add('a')
>>> ''.join(letter if letter in guessed else '-' for letter in word)
'-a---a-'
>>> guessed.add('m')
>>> ''.join(letter if letter in guessed else '-' for letter in word)
'-a--ma-'
>>> guessed.add('e')
>>> ''.join(letter if letter in guessed else '-' for letter in word)
'-a--ma-'
>>> guessed.add('n')
>>> ''.join(letter if letter in guessed else '-' for letter in word)
'-an-man'

How to count vowels and consonants in Python?

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
"""

My anagram code doesn't account for multiple letters

So my code gets two words, and checks if one is the anagram of another one.
However doesn't work if multiple letters are exchanged, although I tried to account for that.
storedword = input("Enter your primary word \t")
global word
word = list(storedword)
word3 = input("Enter anagram word \t")
word3lowercase = word3.lower()
anaw = list(word3lowercase)
counter = int(0)
letterchecker = int(0)
listlength = len(word)
newcounter = int(0)
if len(anaw) != len(word):
print ("not anagram")
if len(anaw) == len(word):
while counter < listlength and newcounter < listlength:
tempcount = 0
if anaw[counter] == word[newcounter]:
temp = word[newcounter]
word[newcounter] = word[tempcount]
word[tempcount]=temp
letterchecker +=1
counter +=1
tempcount +=1
newcounter = int(0)
else:
newcounter +=1
if counter == len(word):
print ("anagram")
else:
print ("not anagram")
I think it's gone somewhere wrong after the if len(anaw) section, for example if the primary word is "hannah", and the secondary word is "hannnn", it thinks it's an anagram.
There is much simpler logic that can be implemented here, even without using sorted and such. Let's assume you have a function anagram:
def anagram(word1, word2):
if len(word1) != len(word2):
return False
def char_count(word):
char_count = {}
for c in word:
char_count[c] = char_count.get(c, 0) + 1
return char_count
cr1 = char_count(word1)
cr2 = char_count(word2)
return cr1 == cr2
You can test this with:
>>> print(anagram("anagram", "aanragm"))
True
>>> print(anagram("anagram", "aangtfragm"))
False
And for future readers, a super simple pythonic solution might be using Counter:
from collections import Counter
>>> Counter(word1) == Counter(word2)
Or using sorted:
>>> sorted(word1) == sorted(word2)
newcounter = int(0)
This is the line that causes the trouble (in the while loop).
Because of it you start checking the word from the beginning again.
I think you want it to be newcounter=letterchecker.
Since already used characters are put to the front of word they are ignored if you start with letterchecker
Tell me if it works
Edit:Checked with example given, seems to work.
Without using sort you could use the following approach. It removes a letter from an array of a characters of the second word. The words are only anagrams if there are no letters left (and the words are the same length to start with and have a length larger than zero):
word1="hannah"
word2="nahpan"
chars1= list(word1)
chars2= list(word2)
if len(chars1)==len(chars2) and len(chars1)>0:
for char in chars1:
if char not in chars2:
break
chars2.remove(char)
if len(chars2)==0:
print "Both words are anagrams"
else:
print "Words are not anagrams"
[EDIT THIS IS JUST FOR PALINDROMES I CANT READ]
Here is something a bit more simple:
storedword = input("Enter your primary word \t")
word3 = input("Enter anagram word \t")
if storedword == word3[::-1]:
print "Is Anagram"
else:
print "Is not anagram"

Categories