This question has already been implemented in Python. I want to rewrite it into a PHP code, instead of combining elements repeatedly ~ That is to say, there are N elements, maybe A + B is equal to 100, and the result is the maximum combination that satisfies the result of no more than 120, just as A + C + D is equal to 191. {Code...} has already been implemented in Python. I want to rewrite it into a PHP code, which is stuck in the combination of non-repeating elements. I 'd like to give a thought ~
That is to say, there are N elements, maybeA
+B
The value is equal to 100, but the result cannot exceed120
The maximum combinationA
+C
+D
Equal to 191.
#-*-Coding = UTF-8-*-import itertoolsloop = [509,838,924,650,604,793,564,651,697,649,747,787,701,605,644] m = 0m_list = [] for I in range (0, len (loop )): # The purpose is to disrupt the sorting and find any possible rets = list (itertools. combinations (loop, I) for ret in rets: # sum the tuples in the iterator s = sum (ret) if s <= 5000 and s> m: # sum m = s # combined list m_list = ret # Maximum print (m) # sum element print (m_list)
Reply content:
This question has already been implemented in Python. I want to rewrite it into a PHP code, instead of combining elements repeatedly ~
That is to say, there are N elements, maybeA
+B
The value is equal to 100, but the result cannot exceed120
The maximum combinationA
+C
+D
Equal to 191.
#-*-Coding = UTF-8-*-import itertoolsloop = [509,838,924,650,604,793,564,651,697,649,747,787,701,605,644] m = 0m_list = [] for I in range (0, len (loop )): # The purpose is to disrupt the sorting and find any possible rets = list (itertools. combinations (loop, I) for ret in rets: # sum the tuples in the iterator s = sum (ret) if s <= 5000 and s> m: # sum m = s # combined list m_list = ret # Maximum print (m) # sum element print (m_list)
You want to test the algorithm.
rets = list(itertools.combinations(loop, i))
It is not suitable to perform this sort of operation directly. if the data size is large, it will inevitably fail. this is a problem with a backpack. for details, refer to the description.
The Knapsack problem (Knapsack problem) is a complete NP problem of combined optimization. The problem can be described as: Given a group of items, each item has its own weight and price. within the limited total weight, how can we choose to make the total price of the item the highest. The name of the question comes from how to choose the most suitable item to place in the given backpack.
Https://zh.wikipedia.org/wiki...
If you want the itertools function in php, you can refer to this
Https://github.com/alts/iter.php