Skip to main content
 首页 » 编程设计

python之寻找以前编写的代码的修订

2025年05月04日15Renyi-Fan

<分区>

我注意到最近我的作业成绩随着 Python 类(class)的进步而越来越低,我想知道是否有人可以帮助我看看我在这些代码片段中做错了什么以及为什么它们是错误的。这可能是一篇很长的文章,但如果能帮助我避免在未来犯这些错误,我们将不胜感激。

def geometric(l): 
    'list(int) ==> bool, returns True if the integers form a geometric sequence' 
    res = False 
    if (l[1] / l[0]) == (l[2] / l[1]): 
        res = True 
    return res 

这是一个被认为是错误的代码。正如代码所说,它接受一个整数列表并返回它们是否在几何序列中。我的书说如果 a1/a0 等于 a2/a1,则序列是几何序列,这对 2、4、8、16 等工作得很好。我刚刚意识到这个问题是它只检查前两个索引和忽略其余数字。我可以写什么来解决这个问题?

def letter2number(grade): 
    '''string ==> int, returns the numeric equivalent to the letter grade, adding 0.3 if the grade contains a + 
    and subtracts 0.3 if the grade contains a -''' 
    res = 0 
    if 'F' in grade: 
        res = 0 
    elif 'D' in grade: 
        res = 1 
    elif 'C' in grade: 
        res = 2 
    elif 'B' in grade: 
        res = 3 
    elif 'A' in grade: 
        res = 4 
    if '+' in grade: 
        res += 0.3 
    elif '-' in grade: 
        res -= 0.3 
    return res 

确切地说,这并没有被认为是错误的,但我猜它比他预期的要长得多。他在文件上写的评论是“#set res to index of grade in grades”,但由于这是一个独立的实验室,我无法寻求帮助。我试图在列表中为每个等级赋予它的值,但我无法正确索引它。

def leap(n): 
    'int ==> bool, returns True if the year is a leap year, False otherwise' 
    res = False 
    if n % 4 == 0 and n % 400 == 0 or not n % 100 == 0: 
        res = True 
    return res 

弄清楚一个 if 语句翻译成“如果年份可以被 4 整除但不能被 100 整除,除非它可以被 400 整除”,这让我感到困惑。显然我写的内容适用于所有奇数,但我真的不明白为什么。