
第一段引用上面的摘要:
本文旨在帮助开发者理解并解决 CS50P Problem Set 8 中 Cookie Jar 类 withdraw 方法在 check50 测试中出现的 "jar's withdraw method removes cookies from the jar's size" 错误。通过分析问题代码和提供的解决方案,详细解释了错误的根源,并给出了正确的实现方法,以确保 withdraw 方法能够正确地从 Cookie Jar 中移除饼干。
在 CS50P 的 Problem Set 8 中,你需要创建一个 Jar 类来模拟一个饼干罐。这个类需要具备初始化、存入饼干 (deposit) 和取出饼干 (withdraw) 的功能。check50 会对你的代码进行一系列测试,以确保其正确性。其中一个常见的错误发生在 withdraw 方法的实现上,导致无法通过测试。
问题分析
根据提供的信息,check50 报错信息为 "jar's withdraw method removes cookies from the jar's size"。这意味着 withdraw 方法在移除饼干时出现了逻辑错误,导致饼干罐的大小计算不正确。
查看原始代码,withdraw 方法的条件判断如下:
def withdraw(self, n):
if n <= self.capacity and n < self.size:
self._size -= n
else:
raise ValueError问题在于 n
解决方案
正确的 withdraw 方法应该只检查取出的饼干数量是否小于或等于当前饼干罐中饼干的数量。因此,应该移除 n
修改后的 withdraw 方法如下:
def withdraw(self, n):
if n <= self.size:
self._size -= n
else:
raise ValueError代码示例
以下是完整的 Jar 类代码,包含了修改后的 withdraw 方法:
class Jar:
def __init__(self, capacity=12):
if capacity < 0: # Corrected the condition to capacity < 0
raise ValueError("Capacity must be non-negative")
self._capacity = capacity
self._size = 0
def __str__(self):
return f"{self.size * '?'}"
def deposit(self, n):
if n < 0:
raise ValueError("Cannot deposit a negative number of cookies")
if n + self.size > self.capacity:
raise ValueError("Exceeds capacity")
self._size += n
def withdraw(self, n):
if n < 0:
raise ValueError("Cannot withdraw a negative number of cookies")
if n > self.size:
raise ValueError("Cannot withdraw more cookies than are in the jar")
self._size -= n
@property
def capacity(self):
return self._capacity
@property
def size(self):
return self._size注意事项
- 确保在初始化 Jar 类时,capacity 是非负数。
- 在 deposit 方法中,确保存入的饼干数量加上已有的饼干数量不超过容量。
- 在 withdraw 方法中,确保取出的饼干数量不超过当前饼干罐中饼干的数量。
- 在 deposit 和 withdraw 方法中,加入对存入和取出负数饼干的判断,避免出现逻辑错误。
总结
通过移除 withdraw 方法中不必要的 n










