Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 13951

Construct all `r`-tuples with two nonzeros

$
0
0

Given an int value val and a tuple length r, I need to create all r-tuples that have d of {+val, -val} and the rest filled up with zeros. With d=2, I can do

val = 7r = 5out = []for i0 in range(r - 1):    for i1 in range(i0 + 1, r):        for v0 in [+val, -val]:            for v1 in [+val, -val]:                t = [0] * r                t[i0] = v0                t[i1] = v1                print(t)
[7, 7, 0, 0, 0][7, -7, 0, 0, 0][-7, 7, 0, 0, 0][-7, -7, 0, 0, 0][7, 0, 7, 0, 0]# ...

but this already feels messy. It's getting worse for larger d. I looked at itertools combinatoric iterators, but none of those seems to help.

Any hints?


Viewing all articles
Browse latest Browse all 13951

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>