0

I was recently given this problem and tasked with coding a solution. My efforts so far have come close but not yet solved it.

Essentially, the problem involves creating a function which is passed a string of numbers (no validation required), for example '12345'.

I have to code the function (using Python preferably) that adds all the consecutive combination of digits. For the above example, this would be:

12345 + 1 + 2 + 3 + 4 + 5
+ 12 + 23 + 34 + 45
+ 123 + 234 + 345
+ 1234 + 2345

I have got some things working, for example:

#code to add the individual numbers
indivInts = [int(d) for d in stringNumber]
for i in indivInts:
        total += i

#code to add 12 + 123 + 12345, etc
for i in range(len(stringNumber)-2):
        s = ''.join([str(x) for x in indivInts[:i+2]])
        print('Adding loop 2: ' + s)
        total += int(s)

The issue I seem to be having is with the 'middle' numbers, ie 234, 34, etc.

The function should be able to take any string of an integer and still work.

2
  • 1
    Just to make sure: Should the first number in the sequence relaly be 123456 or 12345? Commented Sep 2, 2019 at 15:38
  • Apologies, updated the Q now! taken out the 123456 - thanks Tobias Commented Sep 2, 2019 at 15:40

1 Answer 1

4

Basically you need the list of all possible substrings of the original number. You can use a list comprehension with two loops for the lower and upper bounds for this.

>>> s = "12345"
>>> [s[i:k+1] for i in range(0, len(s)) for k in range(i, len(s))]
['1', '12', '123', '1234', '12345', '2', '23', '234', '2345', '3', '34', '345', '4', '45', '5']

Then just get the sum of the previously generated list, converted to int:

>>> sum(map(int, _))
16755

In a single line:

>>> sum(int(s[i:k+1]) for i in range(0, len(s)) for k in range(i, len(s)))
16755

Or as a regular nested loop:

s = "12345"
r = 0
for i in range(0, len(s)):
    for k in range(i, len(s)):
        r += int(s[i:k+1])
print(r)
Sign up to request clarification or add additional context in comments.

3 Comments

Nice code, +1. By the way you're missing "123456" (aka original number) in the sum :)
@Flo Whops, messed up my upper bound. Give me a second... Okay, should be fixed now.
This is much better than what I had been trying... thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.