Reputation: 9
I am trying to create a soduko styled program. A notepad/word document is uploaded into Python and I want Python to check:
Each line (row) has the same number of characters Each column has the same number of characters No characters are repeated twice in either a column or in a row Every character is used once and only once per column and per row
The file uploaded can either be a numerical soduko or an alphabetical soduko.
So far, I have managed to load, open and read the document and append each line of the document as a list. Below I will show my coding for appending to a list:
my_list = [line.strip() for line in open(filename)]
print (my_list)
But this puts all my lines inside a bigger list. For example, if my document read:
1 2 3
2 3 1
3 1 2
It would read my_list as follows: [['1 2 3'], ['2 3 1'], ['3 1 2']]
I'm relatively new to Python and have no idea how to count individual items from a list within a list so this is quite complicated for me.
Any suggestions or tips on how to progress/alter my coding to make this easier for me?
Upvotes: 0
Views: 1265
Reputation: 3
This should take care of most of it. I'm not quite clear on your final spec, but you can probably figure it out from here.
from sets import Set
with open(filename) as f:
my_list = [[x for x in line.strip().split(' ')] for line in f]
#Each row has same number of characters
#Each column has the same number of characters
counts = [len(x) for x in my_list]
if len(Set(counts)) > 1:
print "SAME NUM ERROR"
#No characters are repeated twice in a row
row_len = len(my_list[0])
for row in my_list:
if len(Set(row)) < row_len:
print "ROW REPEAT ERROR"
#No characters are repeated twice in a column
col_len = len(my_list)
for i in range(col_len):
col = [row[i] for row in my_list]
if len(Set(col)) < col_len:
print "COL REPEAT ERROR"
Upvotes: 0
Reputation: 311228
You could split
each line with its own comprehension:
my_list = [[x for x in line.strip().split(' ')] for line in open(filename)]
Note that this oneliner, much like your original code, won't close the file handle it opened. A much safer approach would be to open it separately:
with open(filename) as f:
my_list = [[x for x in line.strip().split(' ')] for line in f]
Upvotes: 1