用codingbat做砖

2024-04-18 01:41:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我是新来的,正在寻找codingbat制作砖块的提示(参见here)。我写了一些代码,但不是所有的东西都能正常工作。也许有人能给我一个提示


任务

我们想做一排几英寸长的砖。我们有许多小砖块(每个1英寸)和大砖块(每个5英寸)。如果可以通过从给定的砖块中选择来实现目标,则返回True。这比看起来要难一点,而且可以在没有任何循环的情况下完成


错误

我有一个问题:

  • make_bricks(3, 1, 9) → False-我的代码是True
  • make_bricks(3, 2, 9) → False-我的代码是True
  • make_bricks(1, 4, 12) → False-我的代码是True

我的代码:

def make_bricks(small, big, goal):
    return small==goal or big==goal or goal%5==small or small*1+big*5==goal or 
    goal%5<=small or small+big!=goal or goal-5!=small or goal-small*1==big*5

make_bricks


Tags: or代码falsetruemakehere情况small
3条回答

如果使用此代码:

def make_bricks(small, big, goal):
    return small==goal or big==goal or goal%5==small or small*1+big*5==goal or 
    goal%5<=small or  goal-small*1==big*5

此代码返回:

make_bricks(3, 1, 9) → False

make_bricks(3, 2, 9) → False

make_bricks(1, 4, 12) → False

但如果使用: goal-5!=small目标=9,小目标=3:

print(9-5!=3)  -> True

or如果其中一条语句为True,则返回True

可以这样简单地解决:

def make_bricks(small, big, goal):
    rem = goal - 5 * min( (goal//5), big )
    if rem > small:
        return False
    return True

表达式min( (goal//5), big )计算所提供的大砖块中可以容纳多少块

当你得出的结果不正确或超出你的预期时,分解步骤以确定哪里出了问题通常是有帮助的。例如,以下是您的代码的分解方式略有不同,因此您可以更轻松地遵循逻辑流程

# ======================================
# Your code written slightly differently
# ======================================

def make_bricks(small, big, goal):
    if small==goal:
        return 1
    elif big==goal:
        return 2
    elif goal%5==small:
        return 3
    elif small*1+big*5==goal:
        return 4
    elif goal%5<=small:
        return 5
    elif small+big!=goal:
        return 6
    elif goal-5!=small:
        return 7
    elif goal-small*1==big*5:
        return 8
    else:
        return False
        
print(make_bricks(3, 1, 9))
print(make_bricks(3, 2, 9))
print(make_bricks(1, 4, 12))

这为您提供了一个提示,告诉您如何识别哪些评估可能没有按照您预期的方式工作。在解释之前,看看你是否能认出罪犯

Evaluation #6 of your code returns True when small + big does not equal the goal. Because the result of this evaluation is True (it does not equal the goal), your script is returning True. In fact, your code will return True for every combination you test.

In order to get to the results you expect, you'll need to correct the offending evaluation and refactor your code a bit to account for the False condition.

一旦代码按您希望的方式工作,您就可以整合操作或重构,以使代码更加精简和高效

相关问题 更多 >