How to sum the result of list.count() - python

I am trying to summarize the number of vowels in a string. How do I total the result of my count?
def count_vowels(string):
vowel = 'aeiou'
for i in list(vowel):
if i in list(string):
print(string.count(i))
count_vowels('abcod') # 2
count_vowels('coliioor') # 5
count_vowels('colour') #3
Current output:
1 first word
1 first word
2 second word
3 second word
2 third word
1 third word

You can use sum() function:
def count_vowels(s):
return sum(ch in 'aeiou' for ch in s)
print(count_vowels('abcod')) # 2
print(count_vowels('coliioor')) # 5
print(count_vowels('colour')) #3
Prints:
2
5
3

First, you're not returning anything from the function, and, your function should use a variable to store the sum and keep increasing it as the loop executes (and you don't need to convert a string to a list to iterate over it, strings are iterable too):
def count_vowels(string):
vowel = 'aeiou'
result = 0
for i in vowel:
if i in string:
result += string.count(i)
return result
A better approach, however, would be to invert your loops:
def count_vowels(string):
vowel = 'aeiou'
result = 0
for i in string:
if i in vowel:
result += 1
return result

I think this will help you (I've commented new lines that are not in your code):
def count_vowels(string):
sum_of_vowels = 0 # new line
vowel = 'aeiou'
for i in list(vowel):
if i in list(string):
sum_of_vowels += string.count(i) # new line
return sum_of_vowels
print(count_vowels('abcod'))
print(count_vowels('coliioor'))
print(count_vowels('colour'))
out:
2
5
3
BETTER WAY:
just do this like this question:
def count_vowels(s):
return sum(vo in 'aeiou' for vo in s)

Related

How to find vowels in the odd positions of a string?

For my code, I have to make a function that counts the number of vowels in the odd positions of a string.
For example, the following will produce an output of 2.
st = "xxaeixxAU"
res = countVowelsOdd(st)
print (res)
For my code, the only problem I have is figuring out how to tell python to count the vowels in the ODD positions.
This is found in the second part of the "if statement" in my code where I tried to make the index odd by putting st[i] %2 == 1. I get all types of errors trying to fix this.
Any idea how to resolve this?
def countVowelsOdd(st):
vowels = "aeiouAEIOU"
count = 0
for i, ch in enumerate(st):
if i in vowels and st[i] % 2 == 1:
count += 1
return count
if i in vowels ...
i is the index, you want the letter
if ch in vowels ...
and then since you have the index, that is what you find the modulo on
if ch in vowels and i % 2 == 1:
enumerate provides you first argument i as position.
def countVowelsOdd(st):
vowels = "aeiouAEIOU"
count = 0
for i, ch in enumerate(st):
if ch in vowels and i % 2 == 1:
count += 1
return count
I don't know if your assignment/project precludes the use of regex, but if you are open to it, here is one option. We can first do a regex replacement to remove all even-positioned characters from the input. Then, do a second replacement to remove all non-vowel characters. Finally, what remains gives us correct vowel count.
st = "xxaeixxAU"
st = re.sub(r'(.).', '\\1', st)
print(st)
st = re.sub(r'[^aeiou]', '', st, flags=re.IGNORECASE)
print(len(st))
This prints:
xaixU
3
Please, have a look at this
In [1]: a = '01234567'
In [2]: print(*(c for c in a[0::2]))
0 2 4 6
In [3]: print(*(c for c in a[1::2]))
1 3 5 7
In [4]: print(*(c in '12345' for c in a[1::2]))
True True True False
In [5]: print(sum(c in '12345' for c in a[1::2]))
3
does it help with your problem?

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

Write a function that returns a list for the number of vowels per line

Define a function lineStats() that takes one parameter:
1. paragraph, a string of words and white spaces
The function returns a list containing the number of vowels in each line.
for example,
t="Apple\npear and kiwi"
print(lineStats(t))
[2,5]
This is what I have. I've gotten the output to be 7 but not to be able to make it 2,5. I tried to make a counter for each line but that didn't work, any suggestions?
def lineStats(paragraph):
vowels = "AEIOUaeiou"
for line in paragraph:
for word in line:
for letter in word:
if letter in vowels:
counter +=1
else:
continue
return counter
t = "Apple\npear and kiwi"
print(lineStats(t))
Here's an adaption of your current code
def lineStats(paragraph):
vowels = "AEIOUaeiou"
counter = []
current_line_count = 0
newline = "\n"
for letter in paragraph:
if letter in vowels:
current_line_count += 1
elif letter == newline:
counter.append(current_line_count)
current_line_count = 0
counter.append(current_line_count)
return counter
t="Apple\npear and kiwi"
def lineStats(p):
#find vowels in each line and sum the occurences using map
return map(sum, [[1 for e in f if e in "AEIOUaeiou"] for f in p.split('\n')])
lineStats(t)
Out[601]: [2, 5]
Try this
Create this function
def temp(x):
return sum(v for k, v in Counter(x).items() if k.lower() in 'aeiuo')
Now
from collections import Counter
print [temp(x) for x in lines.split('\n')]
Changing as little of your code as necessary, other answers offer improvements.
def lineStats(paragraph):
counter = []
vowels = "AEIOUaeiou"
lines = paragraph.split('\n')
for line in lines:
count = 0
for word in line:
for letter in word:
if letter in vowels:
count +=1
else:
continue
counter.append(count)
return counter
t = "Apple\npear and kiwi"
print(lineStats(t)) # [2, 5]
The problem states it wants the result to be a list of counts, so changing counter to be a list that we can append to, then use that list to store the vowel count for each line. That may be the only major change to your code that you need to get the required output.
However, there is the concern of newlines ('\n') in the "paragraph", so we str.split() the paragraph into individual lines before entering the for-loop. This will break the count for each line, instead of the total count that you were getting.

Python code for finding number of vowels in the parameter

I am a python newbie, and am struggling for what I thought was a simple code. My instructions are, Write a function that takes one string parameter word and will return the number of vowels in the string.
Also, just for clarification, supercat is my one string parameter word.
I've been working on this code for some time, and it's gotten a little jumbled.
This is what I have so far.
vowelletters = ["A","E","I","O","U","a","e","i","o","u"]
def isVowel(supercat):
if supercat in vowel:
return True
else:
return False
print isVowel(supercat)
def countvowel(supercat):
count = 0
for index in super cat:
if isVowel(vowelletters): count += 1
return count
y = countvowel(super cat)
print(y)
you can first make the string to test lowercase() so that you don't have to check for capital vowels (this make it more efficient). Next you can count() how many times each vowel is in the teststring and make a final sum() to get a total.
vowelletters = ["a","e","i","o","u"]
teststring= "hellO world foo bAr"
count = sum(teststring.lower().count(v) for v in vowelletters)
print count #6
You can place everything in a function to easily reuse the code.
def countVowels(mystring):
vowelletters = ["a","e","i","o","u"]
return sum(mystring.lower().count(v) for v in vowelletters)
Spaces in variable names not allowed, I would say:
for index in super cat:
and
y = countvowel(super cat)
It looks to me as if your indentation has problems and you left an extra space in there. (super cat instead of supercat)
You also used vowelletters instead of index in countvowel() and forgot to use the global statement in isVowel().
vowelletters = ["A","E","I","O","U","a","e","i","o","u"]
def isVowel(supercat):
global vowelletters
if supercat in vowelletters:
return True
else:
return False
print isVowel(supercat) # This isn't executed
# because it is after a return statement.
def countvowel(supercat):
count = 0
for index in supercat:
if isVowel(index): count += 1
return count
y = countvowel("supercat")
print(y)
how about this:
vowelletters = ("a","e","i","o","u")
def countvowel(word):
word = word.lower()
count = 0
for char in word:
if char in vowelletters:
count += 1
return count
print countvowel('super cat') # prints 3
or using the list comprehension:
vowelletters = ("a","e","i","o","u")
def countvowel(word):
word = word.lower()
vowels = [char for char in word if char in vowelletters]
return len(vowels)
You can simplify this function that you're writing
def countvowel(supercat):
count = 0
for i in range(len(supercat)-1):
if supercat[i] in "AEIOUaeiou":
count += 1
print(count)
You can use sum() and a generator. 
def countVowels(word):
return sum(1 for c in word if c in "AEIOUaeiou")
print(countVowels('supercat'))

Letter Count on a string

Python newb here. I m trying to count the number of letter "a"s in a given string. Code is below. It keeps returning 1 instead 3 in string "banana". Any input appreciated.
def count_letters(word, char):
count = 0
while count <= len(word):
for char in word:
if char == word[count]:
count += 1
return count
print count_letters('banana','a')
The other answers show what's wrong with your code. But there's also a built-in way to do this, if you weren't just doing this for an exercise:
>>> 'banana'.count('a')
3
Danben gave this corrected version:
def count_letters(word, char):
count = 0
for c in word:
if char == c:
count += 1
return count
Here are some other ways to do it, hopefully they will teach you more about Python!
Similar, but shorter for loop. Exploits the fact that booleans can turn into 1 if true and 0 if false:
def count_letters(word, char):
count = 0
for c in word:
count += (char == c)
return count
Short for loops can generally be turned into list/generator comprehensions. This creates a list of integers corresponding to each letter, with 0 if the letter doesn't match char and 1 if it does, and then sums them:
def count_letters(word, char):
return sum(char == c for c in word)
The next one filters out all the characters that don't match char, and counts how many are left:
def count_letters(word, char):
return len([c for c in word if c == char])
One problem is that you are using count to refer both to the position in the word that you are checking, and the number of char you have seen, and you are using char to refer both to the input character you are checking, and the current character in the string. Use separate variables instead.
Also, move the return statement outside the loop; otherwise you will always return after checking the first character.
Finally, you only need one loop to iterate over the string. Get rid of the outer while loop and you will not need to track the position in the string.
Taking these suggestions, your code would look like this:
def count_letters(word, char):
count = 0
for c in word:
if char == c:
count += 1
return count
A simple way is as follows:
def count_letters(word, char):
return word.count(char)
Or, there's another way count each element directly:
from collections import Counter
Counter('banana')
Of course, you can specify one element, e.g.
Counter('banana')['a']
Your return is in your for loop! Be careful with indentation, you want the line return count to be outside the loop. Because the for loop goes through all characters in word, the outer while loop is completely unneeded.
A cleaned-up version:
def count_letters(word, to_find):
count = 0
for char in word:
if char == to_find:
count += 1
return count
You have a number of problems:
There's a problem with your indentation as others already pointed out.
There's no need to have nested loops. Just one loop is enough.
You're using char to mean two different things, but the char variable in the for loop will overwrite the data from the parameter.
This code fixes all these errors:
def count_letters(word, char):
count = 0
for c in word:
if char == c:
count += 1
return count
A much more concise way to write this is to use a generator expression:
def count_letters(word, char):
return sum(char == c for c in word)
Or just use the built-in method count that does this for you:
print 'abcbac'.count('c')
I see a few things wrong.
You reuse the identifier char, so that will cause issues.
You're saying if char == word[count] instead of word[some index]
You return after the first iteration of the for loop!
You don't even need the while. If you rename the char param to search,
for char in word:
if char == search:
count += 1
return count
Alternatively You can use:
mystring = 'banana'
number = mystring.count('a')
count_letters=""
number=count_letters.count("")
print number
"banana".count("ana") returns 1 instead of 2 !
I think the method iterates over the string (or the list) with a step equal to the length of the substring so it doesn't see this kind of stuff.
So if you want a "full count" you have to implement your own counter with the correct loop of step 1
Correct me if I'm wrong...
def count_letter(word, char):
count = 0
for char in word:
if char == word:
count += 1
return count #Your return is inside your for loop
r = count_word("banana", "a")
print r
3
x=str(input("insert string"))
c=0
for i in x:
if 'a' in i:
c=c+1
print(c)
Following program takes a string as input and output a pandas DataFrame, which represents the letter count.
Sample Input
hello
Sample Output
 char Freq.
0 h  1
1 e  1
2 l  2
3 o  1
import pandas as pd
def count_letters(word, char):
return word.count(char)
text = input()
text_split = text.split()
list1 = []
list2 = []
for i in text_split:
for j in i:
counter = count_letters (text, j)
list1.append(j)
list2.append(counter)
dictn = dict(zip(list1, list2))
df = pd.DataFrame (dictn.items(), columns = ['char', 'freq.'])
print (df)

Categories

Resources