【问题标题】:Trying to call a function through an elif and return a flag尝试通过 elif 调用函数并返回标志
【发布时间】:2014-12-10 21:48:04
【问题描述】:

我正在尝试让我的代码通过并在完成一些数学运算后弹出。被求和的文件只是单独行上的数字列表。你能给我一些指导来完成这项工作吗,因为我很难过。

编辑: 我正在尝试使从 main 函数到 Checker 函数的转换正常工作。我还需要一些切片方面的帮助。从文件中导入的数字是这样的:

136895201785
155616717815
164615189165
100175288051
254871145153

所以在我的Checker 函数中,我想将奇数从左到右相加。例如,对于第一个数字,我想添加 169218

完整代码:

def checker(line):

    flag == False
    odds = line[1 + 3+ 5+ 9+ 11]
    part2 = odds * 3
    evens = part2 + line[2 + 4 +6 +8 +10 +12]
    part3 = evens * mod10
    last = part3 - 10
    if last == line[-1]:
        return flag == True


def main():

    iven = input("what is the file name ")
    with open(iven) as f:
        for line in f:
            line = line.strip()
            if len(line) > 60:
                print("line is too long")
            elif len(line) < 10:
                print("line is too short")
            elif not line.isdigit():
                print("contains a non-digit")
            elif check(line) == False:
                print(line, "error")

【问题讨论】:

  • 你能修复缩进错误吗?

标签: python list function if-statement


【解决方案1】:

获取奇数:

odds = line[1::2]

还有事件:

evens = part2 + line[::2]

【讨论】:

    【解决方案2】:

    很遗憾,您的 checker 函数的任何部分都不起作用。看来您可能需要这样的东西:

    def check_sums(line):
        numbers = [int(ch) for ch in line]  # convert text string to a series of integers
        odds = sum(numbers[1::2]) # sum of the odd-index numbers
        evens = sum(numbers[::2]) # sum of the even-index numbers
        if numbers[-1] == (odds * 3 + evens) % 10:
            return True
        else:
            return False
    

    numbers[1::2] 表示“通过第 2 步从 1 到结束获取 numbers 的切片”,而 numbers[::2] 表示“通过第 2 步从开始到结束获取 numbers 的切片”。 (更多解释请参见this questiondocumentation。)

    请注意,模数的运算符是x % 10。我认为这就是您要对evens * mod10 做的事情。在您的原始代码中,您还减去了 10 (last = part3 - 10),但这没有任何意义,所以我省略了这一步。

    这将为您提到的输入行返回以下内容:

    print(check_sums('136895201785')) # >>> False
    print(check_sums('155616717815')) # >>> True
    print(check_sums('164615189165')) # >>> True 
    print(check_sums('100175288051')) # >>> False
    print(check_sums('254871145153')) # >>> False
    

    您的 main 函数很好,只是当您将其命名为 checker 时,它将该函数称为 check

    【讨论】:

    • 步骤 numbers = map(int, line) 是否必要,因为进来的“行”不应该是整数吗?因为当我尝试使用像您这样的代码(甚至复制粘贴您的代码)时,我得到“地图”对象不可下标。而且我不希望它再次成为 list(map())
    • 查看编辑版本。您确实需要转换为int,因为当您读取文件时,您会得到一系列字符串。我用过[int(ch) for ch in line],但我不知道你为什么不想用list(map(int, line)),它做的完全一样。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-13
    • 1970-01-01
    • 2013-03-04
    • 2020-04-10
    • 2018-06-28
    • 2019-03-29
    相关资源
    最近更新 更多