Home > front end >  program to check arithmetic progression from .txt file and print true/false
program to check arithmetic progression from .txt file and print true/false

Time:05-10

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.

example desired 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.

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? Any help would be appreciated.

CodePudding user response:

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

CodePudding user response:

In order to read a file you can use the Python built-in function open() function. documentation here. 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

'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. and the readlines() would give back the lines as a list. You can use string manipulation to split the outputs and use int({varible}) to convert it to an Integer

  • Related