Thursday, 24 July 2014

2 решения

Задание:
Given is array containing N numbers, A[0], A[1], ... A[N-1]. Compute the array B of length N, such that B[i] = A[0]*A[1]*...A[i-1]*A[i+1]...*A[N-1]. Algorithm should work in time O(N), memory O(1) and can't use division.

Решение 1:
Конечно тут не чисто O(N), так как за логарифмом и экспонентой вряд ли O(1).

from math import log, exp
def solve(a):
p = reduce(lambda x, y: x*y, a)
return [int(round( p * exp(-log(x)) )) for x in a]
view raw gistfile1.py hosted with ❤ by GitHub
Решение 2:
А тут чистенько все вроде.
def solve(a):
temp = 1
b = []
for x in a:
temp *= x
b.append(temp)
prev = 1
for i in xrange(len(a) - 2, -1, -1):
b[i + 1] = prev * b[i]
prev *= a[i + 1]
b[0] = prev
return b
view raw gistfile1.py hosted with ❤ by GitHub
Даешь еще решения в комментах!

No comments:

Post a Comment