How to Use itertools to solve the problem of unordered arrangement and combination

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.