Neater way of making indexes?
Anton Vredegoor
anton at vredegoor.doge.nl
Sat May 31 06:18:59 EDT 2003
janeaustine50 at hotmail.com (Jane Austine) wrote:
<snip unliked code>
>I don't like this code too much. Any suggestions?
Repeat this mantra three times:
"the alternatives!, the alternatives!, the alternatives!"
Anton
def indexes(index,bases):
res, remain = [], index
for base in bases[::-1]:
remain, i = divmod(remain, base)
res.append(i)
res.reverse()
return tuple(res)
def test():
from operator import mul
bases = [3,2,4]
n = reduce(mul,bases)
for i in range(n):
print indexes(i,bases),
if not (i+1) % 4: print
if __name__=='__main__':
test()
output:
(0, 0, 0) (0, 0, 1) (0, 0, 2) (0, 0, 3)
(0, 1, 0) (0, 1, 1) (0, 1, 2) (0, 1, 3)
(1, 0, 0) (1, 0, 1) (1, 0, 2) (1, 0, 3)
(1, 1, 0) (1, 1, 1) (1, 1, 2) (1, 1, 3)
(2, 0, 0) (2, 0, 1) (2, 0, 2) (2, 0, 3)
(2, 1, 0) (2, 1, 1) (2, 1, 2) (2, 1, 3)
More information about the Python-list
mailing list