您的问题与数学中的integer partitioning密切相关。
想象一下以一些美元的金额进行更改。例如,如果您以 0.87 美元找零,您可以使用 3 个硬币,每个 25 美分,加上 1 个 10 美分的硬币,再加上 2 个 1 美分的硬币。
import functools
import sys
import copy
class PossibilityMaker:
log_progress = lambda *args, sep=" ", end="\n", print=print, file=sys.stderr:\
print(*args, sep=sep, end=end, file=file)
log_progress = lambda *args, **kwargs: None
@classmethod
def get_possibilities(cls, total:int, denominations):
assert(isinstance(total, int))
denominations = set(denominations)
possibilities = list()
cls.get_possibilities_helper(total, denominations, possibilities, dict())
return possibilities
@classmethod
def get_possibilities_helper(cls, total:int, denominations:set, possibilities:list, partial):
assert(isinstance(total, int))
cls.log_progress("making change for", total, "cent(s) using coins", denominations)
if len(denominations) < 1:
partial = copy.copy(partial)
partial[1] = total
possibilities.append(partial)
cls.log_progress(partial)
del partial
else:
max_denom = max(denominations)
cls.log_progress("largest coin is", max_denom, "cent(s)")
max_coin_quantity = total//max_denom
for coin_quantity in range(max_coin_quantity + 1):
cls.log_progress("Using", coin_quantity, "of coin of size", max_denom)
next_partial = copy.deepcopy(partial)
next_partial[max_denom] = coin_quantity
next_total = total - coin_quantity * max_denom
next_denominations = copy.deepcopy(denominations)
next_denominations.remove(max_denom)
cls.get_possibilities_helper(next_total, next_denominations, possibilities, next_partial)
return
possibilities = PossibilityMaker.get_possibilities(18, [2, 5, 7, 10])
print(60*"#")
print(
"\n".join(
str(possibility) for possibility in possibilities
)
)
输出是:
{10: 0, 7: 0, 5: 0, 2: 0, 1: 18}
{10: 0, 7: 0, 5: 0, 2: 1, 1: 16}
{10: 0, 7: 0, 5: 0, 2: 2, 1: 14}
{10: 0, 7: 0, 5: 0, 2: 3, 1: 12}
{10: 0, 7: 0, 5: 0, 2: 4, 1: 10}
{10: 0, 7: 0, 5: 0, 2: 5, 1: 8}
{10: 0, 7: 0, 5: 0, 2: 6, 1: 6}
{10: 0, 7: 0, 5: 0, 2: 7, 1: 4}
{10: 0, 7: 0, 5: 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, 2: 3, 1: 2}
{10: 1, 7: 0, 5: 0, 2: 4, 1: 0}
{10: 1, 7: 0, 5: 1, 2: 0, 1: 3}
{10: 1, 7: 0, 5: 1, 2: 1, 1: 1}
{10: 1, 7: 1, 5: 0, 2: 0, 1: 1}
您可以将 1 美分硬币视为“剩菜”或“浪费”。我知道你实际上并没有 1 美分硬币,但如果你想象玩家购买了一个无效/浪费的物品,那么所有的东西总是加起来你的 limit = 18。