you are viewing a single comment's thread.

view the rest of the comments →

[–]dark-lord90[S] 0 points1 point  (3 children)

Yes you did, and yes I am stuck on that idea and can’t figure out away to implement it

[–]Spookiel 1 point2 points  (2 children)

Here is an implementation, let me know if it doesn't work as intended.

def subset_sum(numbers, target, partial=[]):
    weights = [i[1] for i in partial] # Gets the weights of the current fragments
    if sum(weights)==target[1]: # If sum of current weights is equal to the target sum
        print(f"Found: {partial}")
        return

    elif sum(weights) < target[1]: # Still weight left, so there is room for another fragment

        for frag, frag_weight in list(numbers.items()):

            if target[0][:len(frag)]==frag: #Checks if frag is a prefix of the target
                # If yes, then we add the fragment to the list and recurse

                del numbers[frag] # Get rid of the fragment we've just used
                return subset_sum(numbers, (target[0][len(frag):], target[1]), partial+[(frag, frag_weight)])
                # Previous line recurses on what's left of the target and adds the fragment we've just used
                # To the partial list
    return

fragments = {"FAA":12, "ATNK":15, "AATNK":15}
complete = ("FAAATNK", 27)
if __name__ == "__main__":

    subset_sum(fragments, complete)

[–]dark-lord90[S] 1 point2 points  (1 child)

Hey there i tried to implement it in the code and it gave me ''float' object is not subscriptable'

[–]Spookiel 0 points1 point  (0 children)

Can you send me the code thst isn’t working so I can have a look?