简体   繁体   English

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

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

I am writing a program that when a user enters a txt file, it reads the data and prints the file, and states if arithmetic progression is true.我正在编写一个程序,当用户输入一个 txt 文件时,它会读取数据并打印文件,并说明算术级数是否为真。

example desired output所需示例 output

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

I have attempted this but am not sure how to read through the file and achieve this desired result.我已经尝试过这样做,但不确定如何通读文件并获得所需的结果。 My current code takes given values and prints the output below.我当前的代码采用给定值并在下面打印 output。

Source File Name: p3_v1.txt
True
False

See bellow my code.请参阅下面的代码。

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]))

How am I able to change my code to print the contents of the txt file and print if each line is true or false?我怎样才能更改我的代码以打印 txt 文件的内容并打印每行是真还是假? Any help would be appreciated.任何帮助,将不胜感激。

In order to read a file you can use the Python built-in function open() function. documentation here .为了读取文件,您可以使用内置的 Python function open() function。此处提供文档。 And this reference will also help这个参考也将有所帮助

An Example Code:示例代码:

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

Example Output示例 Output

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

The read() function will give back the contents as a string. read() function 将返回字符串形式的内容。 and the readlines() would give back the lines as a list.并且readlines()会将这些行作为列表返回。 You can use string manipulation to split the outputs and use int({varible}) to convert it to an Integer您可以使用字符串操作来拆分输出并使用 int({varible}) 将其转换为 Integer

Something like this would work...像这样的东西会起作用......

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))  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM