0

我正在尝试学习 python 并擅长算法。这是我的第一语言。

例如:取“baggage”并分类为“aabeggg”

string = "baggage"
count = [0] * len(string)

for x in string:
    num_value = ord(x)
    count[num_value] += 1

我认为以上是一个开始......但我真的不知道如何去做。

4

3 回答 3

4

collections.Counter是解决这个问题的好方法,但这里有一种方法可以让你朝着你前进的方向走得更远

string = "baggage"
count = [0] * 256  # This should be big enough to hold counters for every 8 bit character

for x in string:
    num_value = ord(x)
    count[num_value] += 1

for i in range(256):  # loop through all the possible 8 numbers
    if count[i]: 
        print chr(i)*count[i]

# you can join them all back into a string like this
newstr = ''.join(chr(i)*c for i,c in enumerate(count))
于 2012-04-18T22:57:41.723 回答
1

让我们在这里看看你的代码。

string = "baggage"
count = [0] * len(string)
# count is now [0,0,0,0,0,0,0]

for x in string:
    num_value = ord(x)
    # ord(x) gives you the ascii number value of a character x
    # So for example ord('b') = 98
    count[num_value] += 1
    # error here since count[98] isn't set.

巴勃罗给了你一个快速的解决方案。我将使用可能更明确的字典写出一个。

string = "baggage"
count = {}

for c in string:
    if c in count:
        count[c] += 1
    else:
        count[c] = 1

print ''.join(count[c]*c for c in sorted(count))
于 2012-04-18T22:26:46.057 回答
0

使用collections.Counter

from collections import Counter
string = 'baggage'
c = Counter(string)
result = ''.join(c[x]*x for x in sorted(c.keys()))

它的工作原理如下:

  • Counter完全符合您的目标count[num_value] += 1
  • sorted(c.keys())按排序顺序为您提供字符
  • c[x]*xc[x]是由char 的副本组成的字符串x
  • ''.join( ... )将每个结果字符串连接成一个字符串
于 2012-04-18T22:43:21.123 回答