简体   繁体   English

如何创建内置函数计数,而无需使用它。 蟒蛇

[英]How to create the built-in function count, without using it. python

I would like to get the exact same result as this code: 我想得到与此代码完全相同的结果:

def histogram(s):
    d = {}

    for w in s: 
        d[w] = s.count(w)

    for k in sorted(d):
        print (k + ': ' + str(d[k]))

But without using any built-in functions. 但不使用任何内置函数。 I only want to use len() and range() and chr() and ord(). 我只想使用len()和range()以及chr()和ord()。

The result of this program when typing in Mississippi is: 在密西西比州键入该程序的结果是:

M: 1
i: 4
p: 2
s: 4

To clear it all upp! 为了清除所有upp!

Write a function histogram(s) that takes a string as a parameter and returns a list with a histogram over the numbers of characters. 编写一个函数直方图,该直方图将字符串作为参数,并返回一个包含直方图的字符数列表。

And a function histprint should be implemented, that takes a list as the function histogram(s) have returned and writes a table on the screen, containing all the characters that was in the string. 并且应该实现一个函数直方图,该函数应在函数直方图返回后获取一个列表,并在屏幕上写一个表,其中包含字符串中的所有字符。 The result should look like: 结果应如下所示:

>>> h=histogram('Mississippi') 
>>> histprint(h) 
M: 1 
i: 4 
p: 2 
s: 4

NO built-in functions! 没有内置功能!

count and Counter are the ways to go but the following should work fine too. countCounter是可行的方法,但是以下方法也可以正常工作。

my = "stackoverflow"
d={}
for l in my:
        d[l] = d.get(l,0) + 1 
print d

{'a': 1, 'c': 1, 'e': 1, 'f': 1, 'k': 1, 'l': 1, 'o': 2, 's': 1, 'r': 1, 't': 1, 'w': 1, 'v': 1}

If you would like to avoid any builtins functions as well as methods such as get. 如果您想避免任何内置函数以及诸如get之类的方法。 You can use try catch which is same as what @d-coder answered. 您可以使用try catch ,它与@ d-coder回答的相同。

Basically you could do: 基本上,您可以这样做:

def histogram(word):
    counter = {}
    for char in word:
        try:
            counter[char] = counter[char] + 1
        except KeyError:
            counter[char] = 1
    return counter

def histprint(h):
    for k in h:
        print k, h[k]

This answer is not different from above and is only removing get with try``except . 这个答案不与上述不同,并且只能去除gettry``except

Also Counter is not a builtin function but a datatype available for particularly this kind of purpose AFAIK. 同样, Counter不是内置函数,而是可用于这种特定目的AFAIK的数据类型。

You can do that by creating a dictionary of letters, and counting the frequency of letters in the word. 您可以通过创建字母词典并计算单词中字母的出现频率来做到这一点。

  • First, create a dictionary of letters, initialized by zero. 首先,创建一个由零初始化的字母字典。
 import string d= dict.fromkeys(string.ascii_letters, 0) #d= dict(zip(string.ascii_letters, [0]*52)) # string.ascii_letters: should give you a list of alphabets (UPPER case,lower case). 

Note: Check the comments 注意:查看评论

Output: 
 {'A': 0, 'C': 0, 'B': 0, 'E': 0, 'D': 0, 'G': 0, 'F': 0, 'I': 0, 'H': 0, 'K': 0, 'J': 0, 'M': 0, >'L': 0, 'O': 0, 'N': 0, 'Q': 0, 'P': 

0, 'S': 0, 'R': 0, 'U': 0, 'T': 0, 'W': 0, 'V': 0, 'Y': 0, 'X': 0, 'Z': 0, 'a': 0, 'c': 0, 'b': 0, 'e': 0, 'd': 0, 'g': 0, 'f': 0, 'i': 0, 'h': 0, 'k': 0, 'j': 0, 'm': 0, 'l': 0, 'o': 0, 'n': 0, 'q': 0, 'p': 0, 's': 0, 'r': 0, 'u': 0, 't': 0, 'w': 0, 'v': 0, 'y': 0, 'x': 0, 'z': 0} 0,'S':0,'R':0,'U':0,'T':0,'W':0,'V':0,'Y':0,'X':0, 'Z':0,'a':0,'c':0,'b':0,'e':0,'d':0,'g':0,'f':0,'i ':0,'h':0,'k':0,'j':0,'m':0,'l':0,'o':0,'n':0,'q': 0,'p':0,'s':0,'r':0,'u':0,'t':0,'w':0,'v':0,'y':0, 'x':0,'z':0}

  • Then, go through every character and add +1 whenever you find it. 然后,遍历每个字符并在找到字符时添加+1
 w= "Mississippi" for x in list(w): d[x]+=1 l= {} for (key, value) in d.iteritems(): if value>0: print key:value 

Output: 输出:

 M : 1 i : 4 p : 2 s : 4 

So your function would be: 因此,您的功能将是:

def histprint(w):
  d= dict.fromkeys(string.ascii_letters, 0)

  for x in list(w):
    d[x]+=1

  l= {}
  for (key, value) in d.iteritems():
    if value>0:
      print key,':',value


histprint("Mississippi")

If you are counting the characters, and you don't distinguish between uppercase and lower case (ie: You assume that M and m refers to same character, and not to Upper 'M' or lower 'm') 如果要计算字符,并且不区分大写和小写(即:假定Mm指的是同一字符,而不是大写“ M”或小写“ m”)

Your algorithm would look like: 您的算法如下所示:

import string

def histprint(w):
  d= dict.fromkeys(string.ascii_lowercase, 0)

  for x in list(w.lower()):
    d[x]+=1

  l= {}
  for (key, value) in d.iteritems():
    if value>0:
      print key,':',value


histprint("Mississippi")
def histogram(s):
    d = {}    
    for i in s:
        try:
            d[i] += 1
        except KeyError:
            d[i] = 1
    # Do you want to implement sorting also without inbuilt method ?
    # Not added sorting here ! `sorted(d)` will give the sorted keys.
    for k, v in d.iteritems():
        print "{} : {}".format(k, v)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在不使用 python 内置 function 和 if 条件的情况下,在列表中计数 5 - count 5 in the list without using python built-in function and if condition 在不使用内置dict数据结构或Python中的计数功能的情况下计算文本文件中字母的频率 - Count frequency of a letter in text file without using built-in dict data structure OR count function in Python 在不使用python内置函数的情况下计算或添加列表元素 - Count or add list elements without using python built-in functions 如何在没有内置 function 的情况下计算列表中字符串的长度? - How to count len of strings in a list without built-in function? 在不使用内置 function 的情况下随机播放 python 列表 - Shuffle a python list without using the built-in function Pythonendswith() 函数,不带内置函数 - Python endswith() function, without the built-in function 如何在不使用迭代器长度的情况下使用 python 中的 slice() 内置 function 获取迭代器的所有元素? - How to get all elements of an iterator using slice() built-in function in python without using the iterator's length? 如何不加区别地仅使用python内置功能(来自两个列表)来创建字典? - How can I create a dictionary without distinction and only using python built-in funtions(from two lists)? 如何从python中的给定数据中删除字符串(不使用任何内置函数)? - How to delete string from given data in python(without using any built-in function)? 如何在不使用内置 transpose() function 的情况下对 Python 中的二维数组进行转置? - How to do transpose of a 2D array in Python, without using the built-in transpose() function?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM