Python:如何使我的 4 色检查器更具可读性
我试图编写一个通用程序来检查 17x17 问题已解决!,17x17 网格的 4 色,没有单色矩形。解决方案链接:17.txt。
这就是我写的:
from itertools import product
def is_solution(myfile,m,n):
""" m-lines, n-columns """
grid = [c.strip() for c in line.split(',')] for line in open(myfile).readlines()]
for x0,y0 in product(xrange(m),xrange(n)):
start = grid[x0][y0]
for x in xrange(x0+1,m):
if grid[x][y0] == start:
for y in xrange(y0+1,n):
if grid[x0][y] == start == grid[x][y]:
return False
return True
print is_solution('17.txt',17,17)
是否有一种更易读、简洁或有效的方式(按优先顺序)来编写此内容?也许对不同的数据结构有不同的方法......因为我现在正在学习Python,所以非常欢迎任何建议。
I was trying to write a general program to check The 17x17 problem SOLVED!, 4-coloring of a17x17 grid with no monochromatic rectangles. Solution link: 17.txt.
This is what I wrote:
from itertools import product
def is_solution(myfile,m,n):
""" m-lines, n-columns """
grid = [c.strip() for c in line.split(',')] for line in open(myfile).readlines()]
for x0,y0 in product(xrange(m),xrange(n)):
start = grid[x0][y0]
for x in xrange(x0+1,m):
if grid[x][y0] == start:
for y in xrange(y0+1,n):
if grid[x0][y] == start == grid[x][y]:
return False
return True
print is_solution('17.txt',17,17)
Is there a more readable, concise or efficient way (in that order of priority) to write this? Maybe a different approach with different data structures... Since i am learning Python at the moment, any advice is very welcome.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我的尝试(从 STDIN 获取文件,可以像
python script.py <17.txt
一样调用):import
ed by another file).My attempt (taking the file from STDIN, can be called like
python script.py < 17.txt
):强制性单行*!
假设您已将 17x17 数据加载到名为
A
的numpy
array
中(请参阅 @robertking 使用 urllib 的答案),您可以使用一行 numpy!* 实际上不要在一行中执行此操作。为了清楚起见,这里对其进行了一些扩展:
Obligatory one-liner*!
Assuming you've loaded the 17x17 data into a
numpy
array
namedA
(see @robertking's answer to use urllib), you can do it with one line with numpy!* Don't actually do this in one-line. Here it is expanded out a bit for clarity:
这是另一种思考方式。
Here is another way to think about it.