I am trying to count the occurrences of each letter of a word
word = input(\"Enter a word\")
Alphabet=[\'a\',\'b\',\'c\',\'d\',\'e\',\'f\',\'g\',\'h\',\'i\'
def string(n):
a=list()
n=n.replace(" ","")
for i in (n):
c=n.count(i)
a.append(i)
a.append(c)
y=dict(zip(*[iter(a)]*2))
print(y)
string("Lets hope for better life")
#Output:{'L': 1, 'e': 5, 't': 3, 's': 1, 'h': 1, 'o': 2, 'p': 1, 'f': 2, 'r': 2, 'b': 1, 'l': 1, 'i': 1}
(if u notice in output 2 L-letter one uppercase and other lowercase..if u want them together look for the code below)
In the output it remove repeated characters ,Drop empty spaces and iterate only on the unique characters. IF you want to count of both uppercase and lowercase together the:
def string(n):
n=n.lower() #either use (n.uperr())
a=list()
n=n.replace(" ","")
for i in (n):
c=n.count(i)
a.append(i)
a.append(c)
y=dict(zip(*[iter(a)]*2))
print(y)
string("Lets hope for better life")
#output:{'l': 2, 'e': 5, 't': 3, 's': 1, 'h': 1, 'o': 2, 'p': 1, 'f': 2, 'r': 2, 'b': 1, 'i': 1}
def char_frequency(str1):
dict = {}
for n in str1:
keys = dict.keys()
if n in keys:
dict[n] += 1
else:
dict[n] = 1
return dict
print(char_frequency('google.com'))
If using libraries or built-in functions is to be avoided then the following code may help:
s = "aaabbc" # sample string
dict_counter = {} # empty dict for holding characters as keys and count as values
for char in s: # traversing the whole string character by character
if not dict_counter or char not in dict_counter.keys(): # Checking whether the dict is
# empty or contains the character
dict_counter.update({char: 1}) # if not then adding the character to dict with count = 1
elif char in dict_counter.keys(): # if the char is already in the dict then update count
dict_counter[char] += 1
for key, val in dict_counter.items(): # Looping over each key and value pair for printing
print(key, val)
Output:
a 3
b 2
c 1
s=input()
t=s.lower()
for i in range(len(s)):
b=t.count(t[i])
print("{} -- {}".format(s[i],b))
Another way could be to remove repeated characters and iterate only on the unique characters (by using set()
) and then counting the occurrence of each unique character (by using str.count()
)
def char_count(string):
freq = {}
for char in set(string):
freq[char] = string.count(char)
return freq
if __name__ == "__main__":
s = "HelloWorldHello"
print(char_count(s))
# Output: {'e': 2, 'o': 3, 'W': 1, 'r': 1, 'd': 1, 'l': 5, 'H': 2}
easy and simple solution without lib.
string=input()
f={}
for i in string:
f[i]=f.get(i,0)+1
print(f)
here is the link for get() https://docs.quantifiedcode.com/python-anti-patterns/correctness/not_using_get_to_return_a_default_value_from_a_dictionary.html