我正在尝试学习 python 并擅长算法。这是我的第一语言。
例如:取“baggage”并分类为“aabeggg”
string = "baggage"
count = [0] * len(string)
for x in string:
num_value = ord(x)
count[num_value] += 1
我认为以上是一个开始......但我真的不知道如何去做。
我正在尝试学习 python 并擅长算法。这是我的第一语言。
例如:取“baggage”并分类为“aabeggg”
string = "baggage"
count = [0] * len(string)
for x in string:
num_value = ord(x)
count[num_value] += 1
我认为以上是一个开始......但我真的不知道如何去做。
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))
让我们在这里看看你的代码。
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))
使用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]*x
c[x]
是由char 的副本组成的字符串x
''.join( ... )
将每个结果字符串连接成一个字符串