您的位置:首页 > 其它

Codility在线学习第一题学习过程

2015-12-01 14:25 441 查看
score: 100

def solution(A):

# write your code in Python 2.7

one = A[0]

two = sum(A[1:])

data = abs(one - two)

for row in range(2, len(A)-1):

one = one + A[row-1]

two = two - A[row-1]

bad = abs(one - two)

if bad < data:

data = bad

return data

score: 50

def solution(A):

# write your code in Python 2.7

data = abs(A[0] - sum(A[1:]))

for row in range(2, len(A)-1):

one = sum(A[0:row])

two = sum(A[row:])

bad = abs(one - two)

if bad < data:

data = bad

return data

score: 41

def solution(A):

# write your code in Python 2.7

data = 0

for row in range(1, len(A)-1):

one = sum(A[0:row])

two = sum(A[row:])

bad = abs(one - two)

if data == 0:

data = bad

if bad < data:

data = bad

return data

score: 25

# you can write to stdout for debugging purposes, e.g.

# print "this is a debug message"

def solution(A):

# write your code in Python 2.7

data = 0

for row in range(1, len(A)-1):

one = sum(map(abs, A[0:row]))

two = sum(map(abs, A[row:]))

bad = abs(one - two)

if data == 0:

data = bad

if bad < data:

data = bad

return data

def solution(A):

# write your code in Python 2.7

data = 0

A = map(abs, A)

for row in range(1, len(A)-1):

one = sum(A[0:row])

two = sum(A[row:])

bad = abs(one - two)

if data == 0:

data = bad

if bad < data:

data = bad

return data

此时朋友给了份100分答案:

def solution(A):

# write your code in Python 2.7

sum_left = A[0]

sum_right = sum(A[1:])

diff_min = abs(sum_left - sum_right)

length = len(A)

i = 1

for i in range(1, length - 1):

sum_left += A[i]

sum_right -= A[i]

diff = abs(sum_left - sum_right)

if(diff_min > diff):

diff_min = diff

return diff_min

score: 16

# you can write to stdout for debugging purposes, e.g.

# print "this is a debug message"

def solution(A):

# write your code in Python 2.7

data = 0

for row in A:

one = sum(map(abs, A[0:A.index(row)]))

two = sum(map(abs, A[A.index(row):]))

bad = abs(one - two)

if (A.index(row)) == 0 or (A.index(row) == (len(A)-1)):

continue

if A.index(row) == 1:

data = bad

if bad < data:

data = bad

return data

非空零索引数组A由N个整数给出。阵列A表示在磁带上的数字。

任何整数p,使得0 <P <N,分裂这个带子分成两个非空部分:A [0],A [1],...,A [P - 1]和A [P],A [ P + 1,...,A [N - 1]。

在不同的两部分之间的值:|(A [0] + A [1] + ... + A [P - 1) - (A [P] + A [P + 1] + .. + A [N - 1])|

换句话说,它是第一部分的总和,而第二部分的总和之间的绝对差。

例如,考虑阵A使得:

A [0] = 3

A [1] = 1

A [2] = 2

A [3] = 4

A [4] = 3

我们可以在四个地方分割该磁带:

P = 1,差值= | 3 - 10 | = 7

P = 2,差= | 4 - 9 | = 5

P = 3,差值= | 6 - 7 | = 1

P = 4,差= | 10 - 3 | = 7

写一个函数:

高清解决方案(一)

,考虑N个整数的非空零索引数组A,返回可以达到的最小差异。

例如,给定:

A [0] = 3

A [1] = 1

A [2] = 2

A [3] = 4

A [4] = 3

该函数应该返回1,如上所述。

假设:

N是内范围内的整数[2 .. 100000];

数组A的每个元素的范围内内的整数-1000 .. 1000]。

复杂:

预计最坏情况下的时间复杂度为O(N);

预期的最坏情况的空间复杂度是O(N),超越输入存储(不计算所需的输入参数的存储)。

输入数组的元素可以被修改。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: