![](/img/trans.png)
[英]count 5 in the list without using python built-in function and if condition
[英]How to create the built-in function count, without using it. python
我想得到與此代碼完全相同的結果:
def histogram(s):
d = {}
for w in s:
d[w] = s.count(w)
for k in sorted(d):
print (k + ': ' + str(d[k]))
但不使用任何內置函數。 我只想使用len()和range()以及chr()和ord()。
在密西西比州鍵入該程序的結果是:
M: 1
i: 4
p: 2
s: 4
為了清除所有upp!
編寫一個函數直方圖,該直方圖將字符串作為參數,並返回一個包含直方圖的字符數列表。
並且應該實現一個函數直方圖,該函數應在函數直方圖返回后獲取一個列表,並在屏幕上寫一個表,其中包含字符串中的所有字符。 結果應如下所示:
>>> h=histogram('Mississippi')
>>> histprint(h)
M: 1
i: 4
p: 2
s: 4
沒有內置功能!
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}
如果您想避免任何內置函數以及諸如get之類的方法。 您可以使用try
catch
,它與@ d-coder回答的相同。
基本上,您可以這樣做:
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]
這個答案不與上述不同,並且只能去除get
與try``except
。
同樣, Counter不是內置函數,而是可用於這種特定目的AFAIK的數據類型。
您可以通過創建字母詞典並計算單詞中字母的出現頻率來做到這一點。
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).
注意:查看評論
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}
+1
。 w= "Mississippi" for x in list(w): d[x]+=1 l= {} for (key, value) in d.iteritems(): if value>0: print key:value
輸出:
M : 1 i : 4 p : 2 s : 4
因此,您的功能將是:
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")
如果要計算字符,並且不區分大寫和小寫(即:假定M
和m
指的是同一字符,而不是大寫“ M”或小寫“ m”)
您的算法如下所示:
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.