我有一个数字27和一个列表NumbersList。我如何从中选出一些数字,NumbersList其中一些是 27。同时使用其中最大的数字。NumbersList 这可以通过尝试所有可能性来实现,但内心深处我知道有一个简单的解决方案,而我对此想得太多了。
27
NumbersList
#available numbers NumbersList = [1,5,9,4,6,8,12,12,1,3,6,8,7,8,2] def GetNumbers(number): global NumbersList tmpList = [] #Some magical code return tmpList #now result have result = GetNumbers(27) # result is [12, 12, 3] # 12+12+3 using most possible greater numbers from "NumbersList"
你可以尝试
NumbersList = [1,5,9,4,6,8,12,12,1,3,6,8,7,8,2] def GetNumbers(number): result = [] for i in sorted(NumbersList, reverse=True): if sum(result) + i <= number: result.append(i) return result
或者如果NumbersList很大,那么你可以通过以下方式减少迭代次数
def GetNumbers(number): result = [] for i in sorted(NumbersList, reverse=True): sum_list = sum(result) if sum_list + i == number: result.append(i) return result elif sum_list + i < number: result.append(i) return result print(GetNumbers(27))
输出
[12, 12, 3]