入坑codewars第12天-Best travel

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_37341950/article/details/84960453

题目一:

John and Mary want to travel between a few towns A, B, C ... Mary has on a sheet of paper a list of distances between these towns. ls = [50, 55, 57, 58, 60]. John is tired of driving and he says to Mary that he doesn't want to drive more than t = 174 miles and he will visit only 3 towns.

Which distances, hence which towns, they will choose so that the sum of the distances is the biggest possible

  • to please Mary and John- ?

Example:

With list ls and 3 towns to visit they can make a choice between:[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60].

The sums of distances are then: 162, 163, 165, 165, 167, 168, 170, 172, 173, 175.

The biggest possible sum taking a limit of 174 into account is then 173 and the distances of the 3 corresponding towns is [55, 58, 60].

The function chooseBestSum (or choose_best_sum or ... depending on the language) will take as parameters t (maximum sum of distances, integer >= 0), k (number of towns to visit, k >= 1) and ls (list of distances, all distances are positive or null integers and this list has at least one element). The function returns the "best" sum ie the biggest possible sum of k distances less than or equal to the given limit t, if that sum exists, or otherwise nil, null, None, Nothing, depending on the language. With C++, C, Rust, Swift, Go, Kotlin return -1.

Examples:

ts = [50, 55, 56, 57, 58] choose_best_sum(163, 3, ts) -> 163

xs = [50] choose_best_sum(163, 3, xs) -> nil (or null or ... or -1 (C++, C, Rust, Swift, Go)

ys = [91, 74, 73, 85, 73, 81, 87] choose_best_sum(230, 3, ys) -> 228

题意:
题目给了choose_best_sum(t, k, ls),ls是一堆距离,题意就是要我们找出ls中k个数相加的最大值且不超过t的大小;
这道题真的麻烦,但是我在网上查到了一个python的函数叫做组合函数,combinations;比如ls=[1,2,3,4],k=2,用了全排列函数就可以找出所有的2个数组合的情况。比如[1,2]、[1,3]、[1,4]、[2,3]……
思路是:
算出所有的距离之和找出最大且不超过ls的大小的距离。
代码如下:
from itertools import combinations
def choose_best_sum(t, k, ls):
    sum2=0
    for dists in combinations(ls,k):
        sum1=sum(dists)
        if sum1>t:
            continue
        sum2=max(sum2,sum1)
    if sum2==0:
        return None
    return sum2

看别人的精简代码:

from itertools import combinations
 
 
def choose_best_sum(t, k, ls):
    return max((s for s in (sum(dists) for dists in combinations(ls, k)) if s <= t), default=None)
  

思路是一样的,但是这个代码是极其精简的。 

猜你喜欢

转载自blog.csdn.net/sinat_37341950/article/details/84960453
今日推荐