How to Use itertools to solve the problem of unordered arrangement and combination
I recently started my battle as a Python rookieCodewarsSo I plan to write down the interesting questions here. Today's first question is"Best Travel":
John and Mary plan to travel to some towns. Mary has listed the distances between these towns, such as ls = [50, 55, 57, 58, 60]. But John doesn't want to drive too tired, so he puts forward two requirements: 1) driving at least a certain distance, such as t = 174 miles; 2) He can only go to three towns.
Which three towns can satisfy John and Mary? (That is, find the three towns whose distance is closest to or equal to t)
This question can be abstracted:
Enter an integer list (ls) and an integer (t:
1. Find all the combinations of any three elements from ls.
2. Calculate the sum of the three elements in each combination
3. If there is a sum less than or equal to t, extract the largest one from it and then output the combination of the largest and corresponding three elements.
4. If it does not exist, None is returned.
Implementation points:
1. unordered permutation and combination:
Combinations Using the itertools Module
2. sum:
Use sum function
3. Calculate the maximum value:
Use max Functions
4. Capture exceptions:
Try-try t
Borrowed from this questionA best solutionImplementation Code:
def choose_best_sum(t, k, ls): import itertools try: return max(sum(combination) for combination in itertools.combinations(ls, k) if sum(combination) <= t) except: return None
In this article, how to use itertools to solve the problem of unordered arrangement and combination is all the content that I shared with you. I hope to give you a reference and support for the customer's house.