Context: I want to make multiple word search grid
I have an Input of lines of text (containing string of numbers and letters) like this:
2 <--- tells how many grids/boxes
3 <--- tells rows/length
4 <--- tells columns/width
catt <--\
aata <--- letters that will fill the box
tatc <--/
cat <--- the word that will be search inside the box
5 <--- and repeat but start with the rows
5
gogog
ooooo
godog
ooooo
gogog
dog
all of that comes in one list as an input
However, I need to pass variables inside. so I assume that I need to split/slice the list into another lists containing all variables that I need.
I think I need to split the variables for cat
and dog
like this:
#variables for cat and dog
rows, cols = [3, 5], [4, 5] #the numbers have to be integer
matrix = [['catt', 'aata', 'tatc'], ['gogog', 'ooooo', 'godog', 'ooooo', 'gogog']]
word = ['cat', 'dog']
those are the variables I need. but I don't know how to split it like that from the input above.
If there are any different ways, feel free to explain. Thank you
CodePudding user response:
If the position of the information in each line is always 'fixed', then the easiest option is to convert the lines to a list, and then reference each line specifically. Something like:
data = text.splitlines()
grids = data[0]
rows = data[1]
cols = data[2]
letters = data[3:7]
repeat = data[7:9]
remain = data[9:]
print(grids, rows, cols, letters, repeat, remain)
CodePudding user response:
I have saved your input in a file called "input.txt" and used the following approach:
with open("input.txt", "r") as f:
lines = [x.strip() for x in f.readlines()]
n_animals, other_lines = int(lines[0]), lines[1:]
rows, cols, matrix, word = [[]] * 4
while len(other_lines) > 0:
rows.append(int(other_lines[0]))
cols.append(int(other_lines[1]))
matrix.append(list(map(lambda x: x[:cols[-1]], other_lines[2:2 rows[-1]])))
word.append(other_lines[2 rows[-1]])
other_lines = other_lines[2 rows[-1] 1:]
if len(matrix) == n_animals:
pass # Do we need to take any action here? like break?
print(rows)
print(cols)
print(matrix)
print(word)
OUTPUT
[3, 5]
[4, 5]
[['catt', 'aata', 'tatc'], ['gogog', 'ooooo', 'godog', 'ooooo', 'gogog']]
['cat', 'dog']
My assumption was that you want to do something with that width variable, hence I have cut every word to cols[-1]
characters. Now, you need to decide what to do if len(matrix) > n_animals
.