0

I need to divide all natural numbers from 1 to n into three sets so that the sum of the numbers in each set is the same. If it can't, return -1 The output should be, for example n = 5:

2
1 4

2
2 3

1
5

I try to do this by my code:

n = int(input())


def divide_numbers(n):
    if n * (n + 1) / 2 % 3 == 0:

        numbers = [i for i in range(1, n+1)]
        total_sum = sum(numbers)
        set_sum = total_sum // 3
        sets = [[], [], []]
        for num in numbers:
            if sum(sets[0]) + num <= set_sum and len(sets[0])<2:
                sets[0].append(num)
            elif sum(sets[1]) + num <= set_sum and len(sets[1])<2:
                sets[1].append(num)
            else:
                sets[2].append(num)
        return sets
    else:
        return -1

a = divide_numbers(n)
if a != -1:
    first = a[0]
    len_first = len(first)
    second = a[1]
    len_second = len(second)
    thired = a[2]
    len_thired = len(thired)
    print(len_first)
    print(*first)
    print(" ")
    print(len_second)
    print(*second)
    print(" ")
    print(len_thired)
    print(*thired)

else: print(a)

but the output is for n = 5:

2
1 2
 
1
3
 
2
4 5

I know that the condition that the sum of the numbers in the set must be equal is not met, how can I fix this?

Proger228
  • 688
  • 10

0 Answers0