Ticket #15609: integer_vector_ranking.patch

File integer_vector_ranking.patch, 1.4 KB (added by f.poloni, 8 years ago)
  • integer_vector.py

    old new  
    99 *   Travis Scrimshaw (2012-05-12) - Updated doc-strings to tell the user of
    1010     that the class's name is a misnomer (that they only contains non-negative
    1111     entries).
     12 *   Federico Poloni (2013) - specialized rank()
    1213"""
    1314#*****************************************************************************
    1415#       Copyright (C) 2007 Mike Hansen <mhansen@gmail.com>,
     
    795796            return False
    796797
    797798        return True
    798  
     799
     800    def rank(self, x):
     801        """
     802        Returns the position of a given element.
     803
     804        INPUT:
     805
     806        - ``x`` - any sequence with sum(x) == n and len(x) == k
     807
     808        TESTS::
     809
     810            sage: IV = IntegerVectors(4,5)
     811            sage: range(IV.cardinality()) == [IV.rank(x) for x in IV]
     812            True
     813        """
     814
     815        n = sum(x)
     816        k = len(x)
     817
     818        if k != self.k:
     819            raise ValueError, "wrong number of elements"
     820
     821        if n != self.n:
     822            raise ValueError, "wrong sum of elements"
     823
     824        r = 0
     825        for i in range(k-1):
     826          k -= 1
     827          n -= x[i]
     828          r += binomial(k+n-1,k)
     829
     830        return r
     831
    799832class IntegerVectors_nkconstraints(CombinatorialClass):
    800833    def __init__(self, n, k, constraints):
    801834        """