开发者

PySchool- List (Topic 6-22)

I am a beginner in python and i am trying to solve some questions about lists. I got stuck on one problem and I am not able to solve it:

Write a funct开发者_如何学编程ion countLetters(word) that takes in a word as argument and returns a list that counts the number of times each letter appears. The letters must be sorted in alphabetical order.

Ex:

>>> countLetters('google')

[('e', 1), ('g', 2), ('l', 1), ('o', 2)]

I am not able to count the occurrences of every character. For sorting I am using sorted(list) and I am also using dictionary(items functions) for this format of output(tuples of list). But I am not able to link all these things.


Use sets !

 m = "google"
 u = set(m)
 sorted([(l, m.count(l)) for l in u]) 


 >>> [('e', 1), ('g', 2), ('l', 1), ('o', 2)]


A hint: Note that you can loop through a string in the same way as a list or other iterable object in python:

def countLetters(word):

  for letter in word:
    print letter

countLetters("ABC")

The output will be:

A
B
C

So instead of printing, use the loop to look at what letter you've got (in your letter variable) and count it somehow.


finally, made it!!!

import collections
def countch(strng):
    d=collections.defaultdict(int)
    for letter in strng:
        d[letter]+=1
    print sorted(d.items())

This is my solution.Now, i can ask for your solutions of this problem.I would love to see your code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜