Memory error as a result of input string processing
I've been getting this error while I try to run my code. If you know, how I can change it, tell me please! Two-three steps...
Failed test #2 of 11. Runtime error
Error:
Traceback (most recent call last):
File "jailed_code", line 30, in <module>
for j in num:
File "jailed_code", line 5, in aP
a = [1]*n
MemoryError
def aP(n):
a = [1]*n
y = -1
v = n
while v > 0:
v -= 1
x = a[v] + 1
while y >= 2 * x:
a[v] = x
y -= x
v += 1
w = v + 1
while x <= y:
a[v] = x
a[w] = y
yield a[:w + 1]
x += 1
y -= 1
a[v] = x + y
y = a[v] - 1
yield a[:w]
lst = []
res = []
input = input().split(' ')
for i in input:
num = aP(int(i))
for j in num:
if len(j) == 3:
lst.append(j)
res.append(len(lst))
lst = []
res = str(res).replace(',', '')
print(res[1:-1])
Ответы (1 шт):
Автор решения: Zhihar
→ Ссылка
что именно делает ваш код?
очень похоже, что там сидит сложность O(n^3) - O(n^4), то очень нехорошо, поэтому надо знать задачу, чтобы давать какой-то совет
кстати ваш код можно слегка упростить
def aP(n):
# основной код функции
res = [len([j for j in aP(i) if len(j) == 3]) for i in map(int, input().split())]
print(*res)
Решение:
Ваш код усложнен избыточно для такой задачи
Вот код который не ест память и работает на несколько порядков быстрее вашего
def aP(n):
count = 0
for i in range(0, n + 1):
for j in range(i + 1, n + 1):
if n - i - j > j:
count += 1
return count
res = [aP(i) for i in map(int, input().split())]
print(*res)