如何在没有内置函数或计数器的情况下使用python确定字符串中字母出现的次数



我确实有一个粗略的想法,使用word和id函数来获取字符串中字母的值,但不知道如何为每一个类似的相同值增加。这是我面试的个人准备。请给我一些想法和建议,没有代码

如果不使用内置函数或计数器,我会跳出框框思考。只要写一条评论,指导用户在办公桌前做些什么。这里只使用了足够的Python来完成工作,而不使用任何内置函数。

"""
Using a pencil, write down the word, then starting at the first letter:
Write down the letter and put a dash or tick or something next to it
Look for that letter in the word, and add additional marks next to the letter to keep track of the count.
When you've reached the end of the word, go to the next letter and repeat the process 
Skip any letters that you have already counted(Otherwise instead of the count of each letter's occurrences, you'll get the factorial of the count!)
"""

用户一个计数器变量,像这样的东西应该让你开始:

>>> count = 0
>>> meaty = 'asjhdkajhskjfhalksjhdflaksjdkhaskjd'
>>> for i in meaty:
...   if i == 'a':
...     count+=1
...
>>> print count
5

如果跟踪多个字母的多次出现,则使用该字母作为存储计数器整数的字典键:

>>> count = {}
>>> for i in meaty:
...   key = i
...   if key in count:
...     count[key]+=1
...   else:
...     count[key]=1
...
>>> count
{'a': 5, 'd': 4, 'f': 2, 'h': 5, 'k': 6, 'j': 6, 'l': 2, 's': 5}

编辑:Meh,没有计数器,没有内置函数,没有堆栈溢出的编码示例?不知道如何计数而不计数,python本质上不是一个内置函数的集合吗?堆栈溢出对实际编码没有帮助吗?

最新更新