This is my solution resulting in an error. Returns 0
PS: I'd still love a fix to my code :)
from collections import Counter
import string
def count_letters(word):
global count
wordsList = string.split(word)
count = Counter()
for words in wordsList:
for letters in set(words):
return count[letters]
word = "The grey old fox is an idiot"
print count_letters(word)
' ▪︎get length (=number of total characters) of the string by using len(text) ▪︎ get number of spaces by using text. count(' ') ▪︎ subtract number of spaces from total length you can do this with one line of code ! happy coding !
Method #1 : Using isspace() + sum() In this, we check for each character to be equal not to space() using isspace() and not operator, sum() is used to check frequency.
To count the spaces in a string:Use the split() method to split the string on each space. Access the length property on the array and subtract 1. The result will be the number of spaces in the string.
def count_letters(word):
return len(word) - word.count(' ')
Alternatively, if you have multiple letters to ignore, you could filter the string:
def count_letters(word):
BAD_LETTERS = " "
return len([letter for letter in word if letter not in BAD_LETTERS])
Simply solution using the sum function:
sum(c != ' ' for c in word)
It's a memory efficient solution because it uses a generator rather than creating a temporary list and then calculating the sum of it.
It's worth to mention that c != ' '
returns True or False
, which is a value of type bool
, but bool
is a subtype of int
, so you can sum up bool values (True
corresponds to 1
and False
corresponds to 0
)
You can check for an inheretance using the mro
method:
>>> bool.mro() # Method Resolution Order
[<type 'bool'>, <type 'int'>, <type 'object'>]
Here you see that bool
is a subtype of int
which is a subtype of object
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With