从 .txt 文件检查算术级数并打印 true/false 的程序

program to check arithmetic progression from .txt file and print true/false

我正在编写一个程序,当用户输入一个 txt 文件时,它会读取数据并打印文件,并说明等差数列是否为真。

示例所需输出

file: something.txt
[1,2,3,4] True
[3,4,7,7] False 
[2,4,6,8,10] True 
so on ..

我已经尝试过,但不确定如何通读文件并获得所需的结果。我当前的代码采用给定值并在下面打印输出。

Source File Name: p3_v1.txt
True
False

看下面我的代码。

name = input('Source File Name: ')

    def is_arithmetic(l):
        delta = l[1] - l[0]
        for index in range(len(l) - 1):
            if not (l[index + 1] - l[index] == delta):
                 return False
        return True

print(is_arithmetic([5, 7, 9, 11]))
print(is_arithmetic([5, 8, 9, 11]))

我如何更改我的代码以打印 txt 文件的内容并打印每行是真还是假?任何帮助将不胜感激。

为了读取文件,您可以使用 Python built-in 函数 open() 函数.文档 here. And this reference 也有帮助

示例代码:

name = input('Source File Name: ')
with open(name) as f:
    lines = f.read()
    print(lines)
    readlines = f.readlines()
    print(readlines)

示例输出

'1\n2\n3\n4\n5\n\n'
['1\n', '2\n', '3\n', '4\n', '5\n', '\n']

read() 函数将返回字符串形式的内容。 readlines() 会将这些行作为列表返回。您可以使用字符串操作来拆分输出并使用 int({varible}) 将其转换为 Integer

像这样的东西会起作用...

name = input('Source File Name: ')

def is_arithmetic(l):
    delta = l[1] - l[0]
    for index in range(len(l) - 1):
        if not (l[index + 1] - l[index] == delta):
            return l, False
    return l, True


# open the containing data
with open(name, 'rt') as txtfile:  

    # read in data and split into lines
    lines = txtfile.read().split('\n') 

#  iterate through the lines one at a time
for line in lines:  

    # convert to integers
    l = [int(i) for i in line.split(' ') if i.isdigit()]  

    # print the output of the is_arithmetic function for the line
    print(is_arithmetic(l))