【问题标题】:Recursion logic to calculate coin change/football score计算硬币变化/足球比分的递归逻辑
【发布时间】:2016-03-26 11:46:24
【问题描述】:

我正在尝试了解在 stackflow 中发布的 question

我试图使用作为答案之一给出的递归逻辑来计算 NFL 分数

score = 10
points = [7, 3, 2]
names = {7: "touchdown", 3: "field goals", 2 : "safeties"}

def count_combs(left, i, comb, add):
    if add: comb.append(add)
    if left == 0 or (i+1) == len(points):

        if (i+1) == len(points) and left > 0:
            comb.append( (left, points[i]) )
            i += 1
        while i < len(points):
            comb.append( (0, points[i]) )
            i += 1
        print " ".join("%d %s" % (n,names[c]) for (n,c) in comb)
        return 1
    cur = points[i]
    return sum(count_combs(left-x*cur, i+1, comb[:], (x,cur)) for x in range(0, int(left/cur)+1))

print count_combs(score, 0, [], None)

出来的值不正确。

0 touchdown 0 field goals 10 safeties

必须是 5 个安全而不是 10 个。

【问题讨论】:

    标签: python python-2.7


    【解决方案1】:

    代码错误地假定points 的最后一个值总是1。在处理金钱时,这可能是一个很好的假设,因为几乎总是会有面额为 1 的硬币,但它不适合您的足球版本的代码。

    错误在这个块中:

         if (i+1) == len(points) and left > 0:
            comb.append( (left, points[i]) )
            i += 1
    

    该块的更正确实现需要以不同的方式做两件事。首先,它需要确保left 可以被points[i] 整除,否则你无法在剩下的点数的情况下获得所需的分数。它还需要在append 调用中使用left/points[i],因为它不能依赖最后一个值为1

    这是一个固定版本的代码,新东西上有 cmets:

    def count_combs(left, i, comb, add):
        if add: comb.append(add)
        if left == 0 or (i+1) == len(points):
            if (i+1) == len(points) and left > 0:
                if left % points[i]: # can't get the exact score with this kind of points
                    return 0         # so give up on this recursive branch
                comb.append( (left/points[i], points[i]) ) # fix the amount here
                i += 1
            while i < len(points):
                comb.append( (0, points[i]) )
                i += 1
            print " ".join("%d %s" % (n,names[c]) for (n,c) in comb)
            return 1
        cur = points[i]
        return sum(count_combs(left-x*cur, i+1, comb[:], (x,cur)) for x in range(0, int(left/cur)+1))
    

    【讨论】:

    • 是的,这个带 1 的东西通常被忽略。我也在this answer 中处理它,尽管在scheme 中。 (仅供参考。)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-14
    • 2016-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多