Reputation: 23
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
Upvotes: 0
Views: 74
Reputation: 4649
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.")
Upvotes: 1