0

Currently im coding to calculate the number of elements in a row for a magic square and im testing it - first row has 3 elements, the second row has 4 elements and the third row has 3 elements im trying to get the code to make sure that all the rows have the same number of elements however im getting displayed the output :

Enter filename :test
[3]
[4]
[3]

Im not sure what it means when the lists are shown "going down" like this, they are all in the same index of 0.

Current Code -

r = input("Enter filename :")
while True:
    try:
        f = open(r,"r")
        break
    except:
        r = input("Enter the correct filename :")

while True: 
    line = f.readline()
    if not line:
        break
    a = line.split(' ')
    totalrow = len(a)
    m = []
    m.append(len(a))
    for x in m: 
        print(m[0])

Im not sure as to how to have these numbers in a list separately so i can compare them and apply validation

hsolo
  • 23
  • 6
  • 3
    Not related to the issue, but `while True: line = readline(); if not line: break` Don't iterate over the lines in a file object this way. Just do `for line in f: ...` – juanpa.arrivillaga Mar 15 '20 at 20:38
  • 1
    Honestly, it isn't clear to me at all what you are expecting. Note, in your loop, you do `for x in m: print(m[0])` so you'll always print only the first element in `m`... but again, I have no idea *what you are trying to do* – juanpa.arrivillaga Mar 15 '20 at 20:41
  • show us the content of file `r` – Mojtaba Kamyabi Mar 15 '20 at 20:42
  • i edited the post to show the contents – hsolo Mar 15 '20 at 20:44
  • 1
    Of course,`m` will always have one element, because you've only ever added one element to it. Furthermore, your code would not produce square-brackets around the numbers that are being printed. Again, it is **not clear what you are trying to do and what output you were expecting** – juanpa.arrivillaga Mar 15 '20 at 20:45
  • 1
    Beside the point, but [a bare `except` is bad practice](https://stackoverflow.com/q/54948548/4518341) – wjandrea Mar 15 '20 at 20:47
  • `m[0]` always return same value use `print(x)` in the last line – Mojtaba Kamyabi Mar 15 '20 at 20:48
  • sorry for the poor explanation, im trying to calculate the number of elements in each row and compare them so that if one row has a different number of elements to the others or if all the rows have a different number of elements an error message can be shown. Currently only the number of elements for the last row gets calculated when i so i was testing around with the "m" to see whats happening. Im trying to get an output such as [3,4,3] instead. – hsolo Mar 15 '20 at 20:54
  • @hsolo right. so, your entire thing could be replaced by `row_lengths = [len(line.split()) for line in f]` Your major problem is that you re-create `m = []` on each iteration of your loop. Again, you shouldn't even be using a while-loop here. That isn't the way you would loop over a file. – juanpa.arrivillaga Mar 15 '20 at 20:56
  • tip: also just use one `while loop` you don't require the second one, have it's contents within the first one, and you want an exception for `FileNotFoundError`. – de_classified Mar 15 '20 at 21:25

1 Answers1

1

You can simply create a list beforehand, iterate over the lines and append the length of the line.split to the list.

# Get the file.
r = input("Enter filename:")
while True:
    try:
        f = open(r, "r")
        break
    except FileNotFoundError:
        print(f"Could not locate a file named {r}.")
        r = input("Enter the correct filename: ")

# Count the rows for each line. 
elements_per_line = []
for line in f:  
    rows = len(line.split(" "))
    elements_per_line.append(rows)

# Do something with that information (`elements_per_line` == [2, 3, 2] now).
if sum(elements_per_line) != len(elements_per_line) * elements_per_line[0]:
    print("✗ Not all lines have the same size!")
else:
    print("✓ All lines have the same size.")
Guimoute
  • 4,407
  • 3
  • 12
  • 28