W
W
weranda2016-07-22 09:58:49
Python
weranda, 2016-07-22 09:58:49

How to determine the sum of the left and right parts of large numbers?

Hello
, I'm facing a simple problem:

From all six-digit numbers, print those whose sums of the left and right parts are equal.

And wrote the solution:
for x in range(100000, 999999):
  x = str(x)
  left = [int(x[0]), int(x[1]), int(x[2])]
  right = [int(x[3]), int(x[4]), int(x[5])]
  if sum(left) == sum(right):
    print(x)

As you can see, the solution to this problem is somewhat crooked. How to solve it correctly?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Anton Fedoryan, 2016-07-22
@weranda

for i in range(100000, 1000000):
  x = [int(item) for item in str(i)]
  if (sum(x[:3]) == sum(x[3:])):
    print(i)

A
abcd0x00, 2016-07-22
@abcd0x00

>>> import operator
>>> 
>>> def split3(x):
...     return (x // 100, x // 10 % 10, x % 10)
... 
>>> def split6(x):
...     return (x // 1000, x % 1000)
... 
>>> pred = lambda x: operator.eq(*map(sum, map(split3, split6(x))))
>>> 
>>> out = list(filter(pred, range(100000, 1000000)))
>>> out[:10]
[100001, 100010, 100100, 101002, 101011, 101020, 101101, 101110, 101200, 102003]
>>>

G
got686, 2016-07-30
@got686

from itertools import product
groups = {i: [] for i in range(1,28)}
for i in range (100, 1000):
    groups[i // 100 + i // 10 % 10 + i % 10].append[i]

results = []
for i in groups:
    results += [x*1000+y for x,y in product(groups[i], repeat=2)]
print(results)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question