用python解决平衡问题

时间:2017-03-21 23:38:36

标签: python

我尝试用我自己的程序解决codility demo问题。 当我自己运行它时,我成功地检测到了平衡。但它始终显示我的答案是不正确的,当鳕鱼评估我的答案。 这是我的代码:

i = 0
for N in range(0, len(A)-1):
    lnum = 0
    rnum = 0
    if N == 0:
        lnum = 0
    elif N ==1:
        lnum = A[0]
    else:
        for num1 in A[:N-1]:
            lnum += num1

    for num2 in A[N+1:]:
        rnum += num2

    if lnum == rnum:
        return N
return -1

任何人都可以向我解释为什么会这样吗? ps:我使用两个if语句,因为当N等于0时,左边的总和等于0,当N等于1时,A[0:0]将不会给我这个数字指数0指向。

1 个答案:

答案 0 :(得分:0)

# Program that let's you find all numbers in any range defined by user
# that can be divided without any reminder by the number also defined by user

print('Find all numbers in range...')

while True:
    try:
        x = int(input('From: ')) # begining of the range
        y = int(input('.. to: ')) # end of the range
        z = int(input('.. that can be divided by: ')) # value of the number to divide by
    except ValueError: # in case of a nonint input
        print('You should enter a valid number!')
        continue

    for a in range(x, y):
        try:
            if a % z == 0:
                print(a, [a / z], end = ' ')
        except ZeroDivisionError: # in case of variable z = 0
            print('You shoudln\'t divide by 0!!')
            break
    break

这应该可以达到95% Codility有自己的代码运行测试用例,因此在您自己的环境中测试代码并不能保证传递代码。