Populate a 5 * 5 list with python
I have a list[5][5] to populate... it looks like a table with 5 columns and 5 rows. Each cell can be either one or zero. I want to find different 2^25 possibility that can exist. Each possiblity is a combination of either 0 or 1 in a 5*5 table/list
How can I do that? With nest开发者_JS百科ed loop or something?
I suggest you start small... with a 1x1 list
first and check that you can display both of the available combinations:
[[0]]
[[1]]
Next up, try a 2x2 list
. There are 16 different list
s to display:
[[0, 0], [0, 0]]
[[0, 0], [0, 1]]
[[0, 0], [1, 0]]
[[0, 0], [1, 1]]
[[0, 1], [0, 0]]
[[0, 1], [0, 1]]
[[0, 1], [1, 0]]
[[0, 1], [1, 1]]
[[1, 0], [0, 0]]
[[1, 0], [0, 1]]
[[1, 0], [1, 0]]
[[1, 0], [1, 1]]
[[1, 1], [0, 0]]
[[1, 1], [0, 1]]
[[1, 1], [1, 0]]
[[1, 1], [1, 1]]
If you've got the algorithm right for 1x1 and 2x2, then you should be able to generalise it to print your 5x5.
Good luck!
Update
Since you appear to be still struggling, here's a little extra help.
Break this problem into smaller problems. I'd start with generating the values. If you ignore the list
notation in my examples above, you'll see that the sequence of values is one that is recognisable to every computer scientist on the planet. It's also pretty easy to generate in Python using bin()
and str.zfill()
.
The second problem is putting them into list
s. This isn't too hard either. Supposing the first value in your sequence is '0000'. You know that your list
s are two rows by two columns. You can put the first two characters into a list and put that list into a list. Then put the next two characters into a list and append that list to the previous one. Done. Repeat for each value in the sequence.
Hope this helps.
You could try:
import itertools
gen = itertools.product((0,1),repeat=25)
To create a generator to get all of the combinations in 1d and then reshape the data as needed.
精彩评论