[codewars_python]Best travel
instructions
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- ?
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
my solution:
from itertools import combinations
def choose_best_sum(t, k, ls):
l = []
for lst in combinations(ls,k):
if sum(lst)<=t:
l.append(lst)
result = [sum(n) for n in l]
if result:
return max(result)
else:
return none
best solution:
import itertools def choose_best_sum(t, k, ls): try: return max(sum(i) for i in itertools.combinations(ls,k) if sum(i)<=t) except: return none
---------------------------------------------------------------------------
itertools库combinations方法可实现排列组合,用法如下:
from itertools import combinations test_data = [100, 76, 56, 44, 89] for x in combinations(test_data, 3): print(x)
打印结果如下:
(100, 76, 56) (100, 76, 44) (100, 76, 89) (100, 56, 44) (100, 56, 89) (100, 44, 89) (76, 56, 44) (76, 56, 89) (76, 44, 89) (56, 44, 89)
推荐阅读
-
[codewars_python]Best travel
-
[codewars_python]Sum of Digits / Digital Root
-
AttributeError: module ‘community‘ has no attribute ‘best_partition‘ 问题解决方法
-
HDU4418 Time travel(期望dp 高斯消元)
-
module ‘community‘ has no attribute ‘best_partition‘ [已解决]
-
台北电脑展Best Choice Award出炉 7nm锐龙要拿年度大奖?
-
C-Travel along the Line ZOJ - 4006题解
-
ElasticSearch多字段查询best_fields和most_fields介绍
-
[PAT*]1023 The Best Polygon (35分)
-
BZOJ1576: [Usaco2009 Jan]安全路经Travel(最短路 并查集)