我一直在尝试和this question一样只是为了好玩,但是在Sage 。我对Mathematica中生成该插图的代码有多短暂印象深刻(我也注意到Mathematica的语言有多丑)。不过,我认为这是练习Sage的好方法。
这就是我所做的:
n=3
A=sum(line([(j, i), (n, i)]) for j in range(n+1) for i in range(n+1))
B=sum(line([(i, j), (i, n)]) for j in range(n+1) for i in range(n+1))
G=Graphics()
G+=A+B
G.show(figsize=[4, 4], axes=False)
result = []
min = int('1'*n, 2)
max = int('1'*n+'0'*n, 2)
combinations = [bin(i)[2:] for i in range(min, max+1)]
for num in combinations:
valid = ''.join(['0']*(2*n-len(num))) + num
zeros = valid.count('0')
ones = valid.count('1')
if zeros == n and ones == n:
result.append(valid)
#At this point all the paths are stored in the variable 'results' in binary form.
#For example '010101' means right, left, right, left, right, left
paths = []
for element in result:
path = [(0, 0)]
for index, direction in enumerate(list(element)):
if direction == '0':
path.append((path[index][0]+1, path[index][1]))
else:
path.append((path[index][0], path[index][1]+1))
paths.append(path)
C=sum(line(p, alpha=0.3, hue=(color/float(len(paths)))) for color, p in enumerate(paths))
T=Graphics()
T+=C
T.show(figsize=[4, 4], axes=False)
在我的结果图像中,所有路径都重叠。在上述问题中,可以清楚地看到路径。我不知道他们是怎么做的,在Sage看到它会很有趣。
你会怎么做,所以代码更短(但遵循良好做法)并且路径不会重叠?