Python algorithm to summ N numbers

Question:

I’m just started in python, trying to solve this:

You need to place "+" between numbers 123…N, to have M as a result

Example:

  1. In: 5 15

    Out: 1+2+3+4+5=15

  2. In: 4 46

    Out: 12+34=46

I was searching all over Internet, but found none.

Asked By: PUser

||

Answers:

This code works only for one + sign.

[1]Code:-

n=input("Input number: ")
target=input("Input the target value: ")
total=0
lis=[str(i) for i in range(1,int(n)+1)]
flag=True
#print(lis)
for i in range(len(lis)):
    #print(lis[:i],lis[i:])
    left_side="".join(lis[:i])
    #print(left_side)
    right_side="".join(lis[i:])
    #print(right_side)
    temp=left_side+"+"+right_side
    total=eval(temp)
    #print(total)
    if total==int(target):
        print(left_side+"+"+right_side+" gives output: "+target)
        flag=False
        break
if flag:  #No target value found
    print("There is no value which sum up to target")

Output:-
#Testcase1: When Target is achievable.

Input number: 4
Input the target value: 46
12+34 gives output: 46

#Testcase2: When Target is not achievable

Input number: 8
Input the target value: 345
There is no value which sum up to target

A correct solution, which works on both examples given in the question and on other problems which require more than one + sign, can be found in Paul Hankin’s answer: https://stackoverflow.com/a/74741043/1400793

Answered By: Yash Mehta

You can solve the problem by doing a depth-first search. This code tries all possible numbers formed from the last digits (n-i+1, n-i+2, …, n), and then recurses to find all solutions for the reduced target. It outputs all solution (since there can be more than one).

def s(n, target):
    for i in range(1, n+1):
        d = int(''.join(str(n-i+j+1) for j in range(i)))
        if i == n and target == d:
            yield f'{d}'
        else:
            for r in s(n - i, target-d):
                yield f'{r}+{d}'


cases = [(4, 46), (5, 15), (6, 174), (4, 1234), (3, 15), (3, 24), (9, 90), (9, 91)]
for c in cases:
    print(f'{c}:', ', '.join(s(*c)))

Output:

(4, 46): 12+34
(5, 15): 1+2+3+4+5
(6, 174): 123+45+6
(4, 1234): 1234
(3, 15): 12+3
(3, 24): 1+23
(9, 90): 12+3+45+6+7+8+9, 1+2+3+4+56+7+8+9
(9, 91):
Answered By: Paul Hankin
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.