【发布时间】:2016-04-04 12:33:21
【问题描述】:
在Ashton String task中,目标是:
将给定字符串的所有不同子字符串排列在 字典顺序并将它们连接起来。打印第 K 个字符 连接的字符串。可以保证,给定的 K 值将是 有效,即会有第 K 个字符。
Input Format:
第一行将包含一个数字 T,即测试用例的数量。第一的 每个测试用例的行将包含一个包含字符的字符串 (a−z) 和第二行将包含一个数字 K。
Output Format:
打印第K个字符(字符串为1索引)
Constraints 是
1 ≤ T ≤ 5
1≤长度≤105
K 将是一个适当的整数。
例如,给定输入:
1
dbac
3
输出将是:c
我已经用这段代码尝试过这个任务,它适用于相对较短的字符串:
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])
有没有办法在不使用导致MemoryError 的过多内存和heapq 推送和弹出的运行时间太慢之间取得平衡?
【问题讨论】:
标签: python string out-of-memory n-gram