Pratham
Pratham

Reputation: 37

How can i print number of times each alphabet occurs in the string?

Well i was trying to write an code for isogram in python as my assignment so i got stuck here
I considered following things
1.All the words entered are in small
2. It only contains alphabets and no special characters or numbers

word =input("enter the word ")
list_of_alphabets = list(word)
no_of_alphabets = len(list_of_alphabets)
for i in range(no_of_alphabets):
  number = list_of_alphabets.count()
  print (number)

I got stuck here now i want the for loop to check whether each alphabet occurs once or not and print number of times each alphabet occurs. If not then it should print not an isogram , and print an isogram if it is. Also if there is some other way to this code i would also like that
PS. Please don't suggest me the code from geeksforgeek as i have already seen it

Upvotes: 0

Views: 740

Answers (3)

DarrylG
DarrylG

Reputation: 17166

Corrections to your posted code.

Changes to your code

word = input("enter the word ")
#list_of_alphabets = list(word)               -- not needed
#no_of_alphabets = len(list_of_alphabets)     -- not needed
#for i in range(no_of_alphabets):             --  change to following
for letter in word:                          # loop through each letter in word
  number = word.count(letter)      
  if number > 1:
    print("Not a isogram")
    break
else:
    # Will enter here only if did not encounter break in above for loop
    print("Is a isogram")

After cleaning up the above we have

word = input("enter the word ")
for letter in word:
  number = word.count(letter)      
  if number > 1:
    print("Not a isogram")
    break
else:
    print("Is a isogram")

Alternative Suggested by Daniel Hao

Using Python sets

word = input("enter the word ")
if len(word) == len(set(word)):
    print("Is a isogram")
else:
    print("Not a isogram")

Upvotes: 3

Samsul Islam
Samsul Islam

Reputation: 2619

as per@dukkee opinion. You can also try this

value ="gallahad"
print({i:value.count(i) for i in value})

Upvotes: 2

dukkee
dukkee

Reputation: 1122

Just use collections.Counter:

>>> c = Counter('gallahad')
>>> c
Counter({'a': 3, 'l': 2, 'g': 1, 'h': 1, 'd': 1})

If you need to check how many specific symbols are in your string, use count method:

>>> 'gallahad'.count("a")
3

Upvotes: 4

Related Questions