Search code examples
pythonfunctionfilecallreadfile

Call function while looping through an external file


I have a function, in this case a function which says if a list with numbers forms an arithmetic progression.

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

My problem is now that I have a .txt file like the following:

1 2 3 4
10 12 54 33
9 4 24 1
14 15 16 17

How can I use my function to go through the file and see if a list/ line forms an arithmetic progression? I know how to open a file and read it but what is the next step and where can I call my function?

fileWithLists = open(input("File name: "))   
rows = filename.readlines()

The output should be for the first and second line

1 2 3 4 True
10 12 54 33 False

and so on


Solution

  • First, correct your function, so it actually uses the given argument by its name. Second, correct your filename assignment. Third:

    for r in rows:
       print (r.strip(), arithmetic([int(i) for i in r.split()]))