我遇到了一个问题,我已经得到了一系列的数字,1,3,5,并需要找到最少的数字,可以添加到一个特定的数字。每个数字都有一个权重,我需要计算出最有效的。例如,如果数字为6,我将需要使用5,1而不是3,3,因为5有更重要的意义。12人的数字为5,5,1,1,而不是3,3,3,3
我已经尝试过实现字典和数组,但问题解决部分是我遇到的问题。
发布于 2019-08-29 10:43:43
一种有效的方法,不依赖于列表中1的存在,是尝试使用尽可能多的最大数字,并递归地尝试获取剩余的:
如果找不到解决方案,该函数将返回None
def solve(numbers, target):
'''Return a list of the largest of numbers whose sum is target,
None if impossible'''
if not numbers:
return None
# make sure that numbers is sorted
numbers = list(sorted(numbers))
# get the largest number and remove it from the list
largest = numbers.pop()
# we start with as many times the largest number as possible
quotient, remainder = divmod(target, largest)
# did we reach the target?
if remainder == 0:
return [largest] * quotient
# if not, try with a deacreasing number of times the largest
# (including 0 times)
for n in range(quotient, -1, -1):
remainder = target - n * largest
# and recursively try to obtain the remainder with the remaining numbers
solution = solve(numbers, remainder)
if solution:
return [largest] * n + solution
else:
return None一些测试:
solve([1, 3, 5], 12)
# [5, 5, 1, 1]
solve([3, 5], 12) # no 1, we have to use smaller numbers
# [3, 3, 3, 3]
solve([7, 3, 4], 15)
# [7, 4, 4]
solve([3, 4], 5) # Impossible
# None发布于 2019-08-29 09:49:03
一直循环,直到n= 0,取掉最大的数,如果n< 0,则取较小的数。
正如This所指出的,如果数组中没有1,可能无法工作,如果是这样的话,您可能想要摆弄if n < 0线。
n = int(input())
a = [1, 3, 5]
ans = []
while n > 0:
n -= max(a)
if n == 0:
ans.append(max(a))
break
if n > 0:
ans.append(max(a))
if n < 0:
n += max(a)
a.pop(a.index(max(a)))
print(ans)https://stackoverflow.com/questions/57706923
复制相似问题