Q:

how to get list of numbers by adding or subtracting given 4 numbers in python

I am trying to get possible numbers from 1 to n, given 4 numbers. by adding or subbtracting 2 or more of the 4 numbers.
e.g. it goes into loop for numlist(1,2,3,16). Below is the code:
def numlist(a,b,c,d):  
    #user input of 4 numbers a,b,c,d
    # assigning variables value of -1. This will be used to provide -1 or +1 or 0
    p=-1 
    q=-1 
    r=-1
    s=-1
    count=0
    myarray=[]

    mysum=a+b+c+d  #sum of given 4 numbers

    for x in range(mysum):
        while count<mysum:
            if p<=1:
                if q<=1:
                    if r <=1:
                        if s<=1:
                            n1=p*a+q*b+r*c+s*d #number to be generated by adding/subtracting
                            s=s+1
                            #print(n1)
                            if n1>0 and (n1 in myarray)==False:
                                #print(n1)
                                myarray.append(n1) #add to myarray if number is positive and not already present
                                myarray.sort()  #sort myarray
                                count=count+1
                            if count==mysum:
                                 break
                        else:
                            s=-1

                        r=r+1
                    else:
                        r=-1

                    q=q+1
                else:
                    q=-1

                p=p+1
            else:
                p=-1

    print(len(myarray),'total')
    print(myarray)
numlist(1,3,4,14)

outputs

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]

but if numlist(1,3,4,19)
it keeps running without ending in output of array. only shows total.
where am I going wrong ?

A:

I think you should rethink your algorithm. Consider this:
from itertools import combinations

def numlist(lst):
    lst = lst + [-i for i in lst]
    result = set()
    for i in range(2, 5):
        result.update(sum(k) for k in combinations(lst, i))
    return sorted(i for i in result if i > 0)

numlist([1, 3, 4, 19])
# [1, 2, 3, 4, 5, 6, 7, 8, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27]

