Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7446705
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 29, 20262026-05-29T12:23:23+00:00 2026-05-29T12:23:23+00:00

I’m having a bit of trouble controlling the results from a data generating algorithm

  • 0

I’m having a bit of trouble controlling the results from a data generating algorithm I am working on. Basically it takes values from a list and then lists all the different combinations to get to a specific sum. So far the code works fine(haven’t tested scaling it with many variables yet), but I need to allow for negative numbers to be include in the list.

The way I think I can solve this problem is to put a collar on the possible results as to prevent infinity results(if apples is 2 and oranges are -1 then for any sum, there will be an infinite solutions but if I say there is a limit of either then it cannot go on forever.)

So Here’s super basic code that detects weights:

import math

data = [-2, 10,5,50,20,25,40]
target_sum = 100
max_percent = .8 #no value can exceed 80% of total(this is to prevent infinite solutions

for node in data:
    max_value = abs(math.floor((target_sum * max_percent)/node))
    print node, "'s max value is ", max_value

Here’s the code that generates the results(first function generates a table if its possible and the second function composes the actual results. Details/pseudo code of the algo is here: Can brute force algorithms scale? ):

from collections import defaultdict

data = [-2, 10,5,50,20,25,40]
target_sum = 100
# T[x, i] is True if 'x' can be solved
# by a linear combination of data[:i+1]
T = defaultdict(bool)           # all values are False by default
T[0, 0] = True                # base case


for i, x in enumerate(data):    # i is index, x is data[i]
    for s in range(target_sum + 1): #set the range of one higher than sum to include sum itself
        for c in range(s / x + 1):  
            if T[s - c * x, i]:
                T[s, i+1] = True

coeff = [0]*len(data)
def RecursivelyListAllThatWork(k, sum): # Using last k variables, make sum
    # /* Base case: If we've assigned all the variables correctly, list this
    # * solution.
    # */
    if k == 0:
        # print what we have so far
        print(' + '.join("%2s*%s" % t for t in zip(coeff, data)))
        return
    x_k = data[k-1]
    # /* Recursive step: Try all coefficients, but only if they work. */
    for c in range(sum // x_k + 1):
       if T[sum - c * x_k, k - 1]:
           # mark the coefficient of x_k to be c
           coeff[k-1] = c
           RecursivelyListAllThatWork(k - 1, sum - c * x_k)
           # unmark the coefficient of x_k
           coeff[k-1] = 0

RecursivelyListAllThatWork(len(data), target_sum)

My problem is, I don’t know where/how to integrate my limiting code to the main code inorder to restrict results and allow for negative numbers. When I add a negative number to the list, it displays it but does not include it in the output. I think this is due to it not being added to the table(first function) and I’m not sure how to have it added(and still keep the programs structure so I can scale it with more variables).

Thanks in advance and if anything is unclear please let me know.

edit: a bit unrelated(and if detracts from the question just ignore, but since your looking at the code already, is there a way I can utilize both cpus on my machine with this code? Right now when I run it, it only uses one cpu. I know the technical method of parallel computing in python but not sure how to logically parallelize this algo)

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-29T12:23:24+00:00Added an answer on May 29, 2026 at 12:23 pm

    You can restrict results by changing both loops over c from

    for c in range(s / x + 1):  
    

    to

    max_value = int(abs((target_sum * max_percent)/x))
    for c in range(max_value + 1):
    

    This will ensure that any coefficient in the final answer will be an integer in the range 0 to max_value inclusive.

    A simple way of adding negative values is to change the loop over s from

    for s in range(target_sum + 1):
    

    to

    R=200 # Maximum size of any partial sum
    for s in range(-R,R+1):
    

    Note that if you do it this way then your solution will have an additional constraint.
    The new constraint is that the absolute value of every partial weighted sum must be <=R.

    (You can make R large to avoid this constraint reducing the number of solutions, but this will slow down execution.)

    The complete code looks like:

    from collections import defaultdict
    
    data = [-2,10,5,50,20,25,40]
    
    target_sum = 100
    # T[x, i] is True if 'x' can be solved
    # by a linear combination of data[:i+1]
    T = defaultdict(bool)           # all values are False by default
    T[0, 0] = True                # base case
    
    R=200 # Maximum size of any partial sum
    max_percent=0.8 # Maximum weight of any term
    
    for i, x in enumerate(data):    # i is index, x is data[i]
        for s in range(-R,R+1): #set the range of one higher than sum to include sum itself
            max_value = int(abs((target_sum * max_percent)/x))
            for c in range(max_value + 1):  
                if T[s - c * x, i]:
                    T[s, i+1] = True
    
    coeff = [0]*len(data)
    def RecursivelyListAllThatWork(k, sum): # Using last k variables, make sum
        # /* Base case: If we've assigned all the variables correctly, list this
        # * solution.
        # */
        if k == 0:
            # print what we have so far
            print(' + '.join("%2s*%s" % t for t in zip(coeff, data)))
            return
        x_k = data[k-1]
        # /* Recursive step: Try all coefficients, but only if they work. */
        max_value = int(abs((target_sum * max_percent)/x_k))
        for c in range(max_value + 1):
           if T[sum - c * x_k, k - 1]:
               # mark the coefficient of x_k to be c
               coeff[k-1] = c
               RecursivelyListAllThatWork(k - 1, sum - c * x_k)
               # unmark the coefficient of x_k
               coeff[k-1] = 0
    
    RecursivelyListAllThatWork(len(data), target_sum)
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm having a bit of trouble getting the right results from a query. At
I'm having bit of a trouble selecting correct values from my mysql sql server.
I'm having a bit of trouble getting the desired functionality from my function... Basically,
Having a bit of trouble using the List.Find with a custom predicate i have
I'm having a bit of trouble iterating and retrieving width() values. $(.MyClass).each( function ()
having a bit of trouble adding some data to a database. I have the
Im having a bit of trouble changing the the weather degrees from fahrenheit to
I'm having a bit of trouble retrieving body from a wcf message. I am
I'm having a bit of trouble with entering data into several columns of a
i am having a bit of trouble with DataInputStreams, So i have data coming

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.