Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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))  
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading