私はPythonを初めて使用するので、非常に簡単なものを求めているかもしれませんが、Pythonの方法で問題を考えることはできません。
圧縮された文字列があります。アイデアは、キャラクターが4〜15回繰り返される場合、次の変更を加えることです。
'0000' ---> '0|4'
15回を超える場合は、スラッシュと2桁の数字を使用して金額を表します(16進値を使用)。
'00...(16 times)..0' ---> '0/10'
したがって、他の言語に慣れているので、私のアプローチは次のとおりです。
def uncompress(line):
verticalBarIndex = line.index('|')
while verticalBarIndex!=-1:
repeatedChar = line[verticalBarIndex-1:verticalBarIndex]
timesRepeated = int(line[verticalBarIndex+1:verticalBarIndex+2], 16)
uncompressedChars = [repeatedChar]
for i in range(timesRepeated):
uncompressedChars.append(repeatedChar)
uncompressedString = uncompressedChars.join()
line = line[:verticalBarIndex-1] + uncompressedString + line[verticalBarIndex+2:]
verticalBarIndex = line.index('|') #next one
slashIndex = line.index('/')
while slashIndex!=-1:
repeatedChar = line[slashIndex-1:slashIndex]
timesRepeated = int(line[slashIndex+1:verticalBarIndex+3], 16)
uncompressedChars = [repeatedChar]
for i in range(timesRepeated):
uncompressedChars.append(repeatedChar)
uncompressedString = uncompressedChars.join()
line = line[:slashIndex-1] + uncompressedString + line[slashIndex+3:]
slashIndex = line.index('/') #next one
return line
Pythonでは文字列は不変であり、「|」がなくなるまで行の内容を常に変更しているため、これは間違っていると思います。または「/」が存在します。
UserStringが存在することは知っていますが、もっと簡単でPython風の方法があると思います。これは、学ぶのに最適です。
何か助けはありますか?