中/低速ランタイム、目標はである:克服MemoryError <a href="https://www.hackerrank.com/challenges/ashton-and-string" rel="nofollow">Ashton String task</a>でアシュトンストリングタスク
が 辞書式順序で指定された文字列のすべての異なるサブストリングを配置し、それらを連結します。連結された文字列の のK番目の文字を表示します。与えられたKの値は であり、すなわちK番目の文字が有効であることが保証される。
Input Format
:
最初の行は、テストケースの数T即ち番号を含むことになります。各テストケースは、文字 (-z)を含む文字列が含まれ、第二行番号K.
Output Format
を含有するであろう最初の ライン:
プリントK番目の文字(文字列であります索引付け1)
そしてConstraints
は
あります1≦T≦5
1≦長さ≦105
Kは適切な整数になります。私はこのコードでタスクを実行しようとしましたし、それが比較的短い文字列のために働くc
:
1 dbac 3
出力は次のようになります。入力与え例えば
、
from itertools import chain
def zipngram(text, n=2):
words = list(text)
return zip(*[words[i:] for i in range(n)])
for _ in input():
t = input()
position = int(input())-1 # 0th indexing
chargrams = chain(*[zipngram(t,i) for i in range(1,len(t)+1)])
concatstr = ''.join(sorted([''.join(s) for s in chargrams]))
print (concatstr[position])
入力ファイルが次のようになっていれば:http://pastebin.com/raw/WEi2p09H、出力は
l
s
y
h
s
インタプリタはMemoryError
がスローされます。
Traceback (most recent call last):
File "solution.py", line 11, in <module>
chargrams = chain(*[zipngram(t,i) for i in range(1,len(t)+1)])
File "solution.py", line 11, in <listcomp>
chargrams = chain(*[zipngram(t,i) for i in range(1,len(t)+1)])
File "solution.py", line 6, in zipngram
return zip(*[words[i:] for i in range(n)])
File "solution.py", line 6, in <listcomp>
return zip(*[words[i:] for i in range(n)])
MemoryError
MemoryErrorを解決することができますか?それは別の方法でネイティブのpython2またはpython3を使用して解決可能ですか?
私はheapq
を使用してスタックを剪定によってMemoryError
を解決しようとしたが、今では押して、あまりにも多くのメモリを占有するのではなく、ヒープをポップユーバー遅いランタイムに入ります。
from itertools import chain
import heapq
t = int(input())
s = list(input())
k = int(input())
stack = []
for n in range(1,len(s)+1):
for j in range(n):
ngram = (''.join(s[j:]))
ngram_len = len(ngram)
# Push the ngram into the heapq.
heapq.heappush(stack, ngram)
pruned_stack = []
temp_k = 0
# Prune stack.
while stack != [] and temp_k < k:
x = heapq.heappop(stack)
pruned_stack.append(x)
temp_k+=len(x)
# Replace stack with pruend_stack.
stack = pruned_stack
print (''.join(chain(*pruned_stack))[k])
heapq
を押してポップでそれがMemoryError
につながることをあまりにも多くのメモリと遅すぎるランタイムを使用していない間のバランスをとる方法はありますか?
この入力を試してください:http://pastebin.com/raw/WEi2p09H? MemoryErrorにも行きますか? – alvas
@alvas私のコードを試してください、それはメモリエラーを取得し、正しい結果を返します –
忍耐、あなたが持っている必要があります。来る、彼らは、賞金が近づいたときに投票する。 – alvas