[英]How do I count the number of times each alphabet occurs in a string without using collection types?
[英]How can i print number of times each alphabet occurs in the string?
好吧,我试图在 python 中为等值线编写代码作为我的任务,所以我被困在这里
我考虑过以下事情
1.所有输入的字都是小字
2.它只包含字母,没有特殊字符或数字
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)
我现在被困在这里,我希望 for 循环检查每个字母是否出现一次并打印每个字母出现的次数。 如果不是,那么它不应该打印等值图,如果是,则打印等值图。 另外,如果此代码有其他方法,我也希望
PS。 请不要向我推荐来自 geeksforgeek 的代码,因为我已经看过了
只需使用collections.Counter
:
>>> c = Counter('gallahad')
>>> c
Counter({'a': 3, 'l': 2, 'g': 1, 'h': 1, 'd': 1})
如果您需要检查字符串中有多少特定符号,请使用count
方法:
>>> 'gallahad'.count("a")
3
更正您发布的代码。
对代码的更改
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")
清理完上面我们有
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")
Daniel Hao 建议的替代方案
使用 Python套
word = input("enter the word ")
if len(word) == len(set(word)):
print("Is a isogram")
else:
print("Not a isogram")
根据@dukkee 的意见。 你也可以试试这个
value ="gallahad"
print({i:value.count(i) for i in value})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.