It’s the case in my domain. We do neuroimaging research and our datasets often have 5, 6, 7 dimensions or more, depending on what we’re trying to do. And if you’re trying to do the same thing to every element in a 5-D matrix (and it’s not something that can be vectorized), there’s not much else to do but write five nested loops.
import extended as xt
import numpy as np
from tqdm import tqdm
import sympy as sp
sum([int(''.join([str(z) for z in y[0,:3]])) for y in [xt.nest(lambda f: [[np.vstack([g[:f[1]],[[w[x] for x in range(9)]],g[f[1]+1:]]) for g in f[0] for l in [np.array([g[:3,:3],g[:3,3:6],g[:3,6:],g[3:6,:3],g[3:6,3:6],g[3:6,6:],g[6:,:3],g[6:,3:6],g[6:,6:]]).reshape([3,3,9])] for p in [[h([k,l[f[1]//3, m//3],g[f[1]]]) for m,k in enumerate(g.T)]] for q in [[n for n,o in enumerate(g[f[1]]) if o==0]] for s in [[n for n,o in enumerate(g[f[1]]) if o!=0]] for t in sp.utilities.iterables.cartes(*[p[r] for r in q]) for w in [{**dict(zip(q,t)),**{u:g[f[1]][u] for u in s}}] if len(t)==len(np.unique(t))], f[1]+1],([[e],0]),9)[0][0] for h in [lambda i: [j for j in range(1,10) if j not in sp.utilities.iterables.flatten(i)]] for a in [open('sudoku.txt').read()+'\n'] for b in tqdm(a.split('Grid')[1:],position=0,leave=True) for e in [np.array([[int(d) for d in c] for c in b.split('\n')[1:-1]])]]])
Say you have an apple orchard full of trees with ripe apples on them.
nested loops: I’m going to pick each apple one at a time from this tree, then go to the next tree and pick those apples, and so on until I’ve picked all the apples.
vectorization: I’m going to hire one person for every tree and ask them to pick all the apples in parallel and put them in the truck when they are done.
I mean if you absolutely had to nest 4 or more loops for some odd reason you should just call another function with the loops in it and do i,j,k, again. You get that deep nested in for loops your code will start to spaghettify.
I use Inconsolata. It looks like normal font but makes a point to be monspaced and have nothing look similar to each other. You can get it from google fonts. https://en.m.wikipedia.org/wiki/Inconsolata
View all comments
Show parent comment
57
u/MattTheGr8 Jun 06 '20
I do a weird thing and skip L and go right to M, to avoid confusion between lowercase L and numeral 1, which look identical in some monospaced fonts.