Last active
July 23, 2018 16:02
-
-
Save mtao/49299124e58242bc87cdb677fa3b425e to your computer and use it in GitHub Desktop.
coroutine-based tool for iterating high order tensors
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def make_range(s): | |
if type(s) == range: | |
return s | |
elif type(s) == slice: | |
return range(s.start,s.stop,s.step if s.step else 1) | |
elif type(s) == tuple: | |
return range(*s) | |
else: | |
return range(s) | |
def iterate(s): | |
s=tuple(map(make_range,s)) | |
def _iter(s): | |
if not s: | |
yield tuple() | |
if len(s) == 1: | |
for i in s[0]: | |
yield (i,) | |
else: | |
S,ss = s[0], s[1:] | |
for i in S: | |
ii = (i,) | |
for f in iterate(ss): | |
yield ii + f | |
for _ in _iter(s): | |
yield _ | |
if __name__ == "__main__": | |
print(list(iterate((5,10)))) | |
print(list(iterate((slice(10,20,None),)))) | |
print(list(iterate((slice(10,20,5),)))) | |
for m in iterate((slice(1,10),slice(20,25),slice(30,40))): | |
print(m) | |
print(list(iterate(((0,5),10)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment