如何简化这个很长的 if 语句?
如何简化这个 if 语句?它产生一个加号: https://i.sstatic.net/PtHO1.png
如果语句完成,则块设置在 x 和 y 坐标处。
for y in range(MAP_HEIGHT):
for x in range(MAP_WIDTH):
if (x%5 == 2 or x%5 == 3 or x%5 == 4) and \
(y%5 == 2 or y%5 == 3 or y%5 == 4) and \
not(x%5 == 2 and y%5 == 2) and \
not(x%5 == 4 and y%5 == 2) and \
not(x%5 == 2 and y%5 == 4) and \
not(x%5 == 4 and y%5 == 4):
...
How can this if-statement be simplified? It makes a plus sign:
https://i.sstatic.net/PtHO1.png
If the statement is completed, then a block is set at the x and y coordinates.
for y in range(MAP_HEIGHT):
for x in range(MAP_WIDTH):
if (x%5 == 2 or x%5 == 3 or x%5 == 4) and \
(y%5 == 2 or y%5 == 3 or y%5 == 4) and \
not(x%5 == 2 and y%5 == 2) and \
not(x%5 == 4 and y%5 == 2) and \
not(x%5 == 2 and y%5 == 4) and \
not(x%5 == 4 and y%5 == 4):
...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
这是一样的:
This is the same:
基本上你正在平铺一个 5x5 的二进制图案。这是一个清晰的表达:
这是一种非常简单且通用的方法,可以轻松修改模式。
Basically you're tiling a 5x5 binary pattern. Here's a clear expression of that:
This is a very simple and general approach which would allow the pattern to be easily modified.
有两个简单的修复:
x % 5
和y % 5
的结果in
或链接<
> 来测试这些值:此外,对
<= 4
(或<5
)的测试实际上是多余的,因为 每个 值code>lx 和ly
将是lx
和ly
将是lx
和ly
5.或者您可以只保留实际允许的元组的列表:
There are two trivial fixes:
x % 5
andy % 5
in
or chained<
to test the values:Additionally, the test for
<= 4
(or< 5
) is actually redundant because every value oflx
andly
will be < 5.Or you may just keep a list of the actually allowed tuples:
基于康拉德的答案,您可以进一步简化它:
Building on Konrad's answer, you can simplify it further:
康拉德的第二个答案:-
可能是最好的一个。
不过,我会贡献:-
Konrad's second answer:-
is probably the best one.
However, I'll contribute:-
优化此类逻辑函数的一般解决方案是卡诺图。您的真值表将是您想要的文字加形状,其中行和列是您的模块化测试。
The general solution to optimizing a logic function like this is a Karnaugh map. Your truth table would be the literal plus shape you want with rows and columns being your modular tests.