[英]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. count
和Counter
是可行的方法,但是以下方法也可以正常工作。
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
. 这个答案不与上述不同,并且只能去除get
与try``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. 您可以通过创建字母词典并计算单词中字母的出现频率来做到这一点。
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}
+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') 如果要计算字符,并且不区分大写和小写(即:假定M
和m
指的是同一字符,而不是大写“ 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.