我想找到一种有效的算法,将整数除以最大,最小范围内的某个值。应该尽可能少的值。
例如: max = 7,min = 3 然后
8 = 4 + 4
9 = 4 + 5
16 = 5 + 5 + 6 (not 4 + 4 + 4 + 4)
修改
为了更清楚,让我们举一个例子。假设你有一堆苹果,你想把它们装进篮子里。每个篮子可以包含3到7个苹果,并且您希望使用的篮子数量尽可能少。
**我提到价值应该均分,但这并不重要。我更担心的是篮子数量减少。
答案 0 :(得分:1)
这让我觉得这是一个有趣的问题,所以我去了解快速解决方案。我认为这可能是一个有趣的起点,它会为您提供尽可能少的数字或尽可能相似的数字的有效解决方案,所有这些都在min_bound定义的范围内和max_bound number = int(输入("数字:")) min_bound = 3 max_bound = 7
def improve(solution):
solution = list(reversed(solution))
for i, num in enumerate(solution):
if i >= 2:
average = sum(solution[:i]) / i
if average.is_integer():
for x in range(i):
solution[x] = int(average)
break
return solution
def find_numbers(number, division, common_number):
extra_number = number - common_number * division
numbers_in_solution = [common_number] * division
if extra_number < min_bound and \
extra_number + common_number <= max_bound:
numbers_in_solution[-1] += extra_number
elif extra_number < min_bound or extra_number > max_bound:
return None
else:
numbers_in_solution.append(extra_number)
solution = improve(numbers_in_solution)
return solution
def tst(number):
try:
solution = None
for division in range(number//max_bound, number//min_bound + 1): # Reverse the order of this for numbers as close in value to each other as possible.
if round (number / division) in range(min_bound, max_bound + 1):
solution = find_numbers(number, division, round(number / division))
elif (number // division) in range(min_bound, max_bound + 1): # Rarely required but catches edge cases
solution = find_numbers(number, division, number // division)
if solution:
print(sum(solution), solution)
break
except ZeroDivisionError:
print("Solution is 1, your input is less than the max_bound")
tst(number)
for x in range(1,100):
tst(x)
此代码只是为了展示一个想法,我确信可以调整它以获得更好的性能。