We call the set of sequences of length n
with k
1's binseq(n,k)
. This problem can then be solved recursively, as follows:
- Base case: If
S
has length 1, it's in position 1. - If
S
starts with a 0, its position is the same as the position oftail(S)
(S
with the first element removed) inbinseq(n-1, k)
. - If
S
starts with a 1, its position is equal to the position oftail(S)
inbinseq(n-1, k-1)
plus the number of sequences inbinseq(n-1, k)
.
In python code:
#!/usr/bin/env python
def binom(n, k):
result = 1
for i in range(1, k+1):
result = result * (n-i+1) / i
return result
def lexpos(seq):
if len(seq) == 1:
return 1
elif seq[0] == 0:
return lexpos(seq[1:])
else:
return binom(len(seq)-1, seq.count(1)) + lexpos(seq[1:])
Or the iterative version, as suggested by Abhishek Bansal:
def lexpos_iter(seq):
pos = 1
for i in xrange(len(seq)):
if seq[i] == 1:
pos += binom(len(seq)-i-1, seq[i:].count(1))
return pos