0

私はPythonを学び、アルゴリズムを上手にしようとしています。これが私の母国語です。

例:「手荷物」を受け取り、「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( ... )結果の各文字列を1つの文字列に結合します
于 2012-04-18T22:43:21.123 に答える