# Ticket #14126: trac_14126-count_linear_extensions_of_a_poset-csar.patch

File trac_14126-count_linear_extensions_of_a_poset-csar.patch, 2.5 KB (added by csar, 7 years ago)
• ## sage/categories/finite_posets.py

```# HG changeset patch
# User Sebastian Csar <sacsar@gmail.com>
# Date 1360949553 18000
# Node ID 8d3ba5344778bb2beb688d885eefc25e63239b92
# Parent  ec1fb07db6e23f9fbd4c34f0d48198d08ec76473
#14126: Add a function to count the number of linear extensions of a poset

diff --git a/sage/categories/finite_posets.py b/sage/categories/finite_posets.py```
 a from sage.categories.category import Category from sage.categories.posets import Posets from sage.categories.finite_enumerated_sets import FiniteEnumeratedSets from sage.misc.cachefunc import cached_function class FinitePosets(Category): r""" sage: list(A) [[], [0], [1], [1, 2], [1, 3], [2], [3], [4]] """ @cached_method def number_of_linear_extensions(self): """ Returns the number of linear extensions of ``self``, that is the number of ways the partial order can be extended to a total order. This function works by recursing through the order ideals with a cache. As a result, its complexity in time and memory is `O(n2^n)`. An alternative way to compute the number of linear extensions is to use the `cardinality` method of the `LinearExtensionsOfPoset` class, which uses `_cardinality_from_iterator` and is `O(n)` in memory and `O(n!)` in time. EXAMPLES:: sage: P = Posets.BooleanLattice(3) sage: P.number_of_linear_extensions() 48 sage: P.linear_extensions().cardinality() 48 sage: P = Posets.AntichainPoset(4) sage: P.number_of_linear_extensions() 24 sage: P = Posets.ChainPoset(4) sage: P.number_of_linear_extensions() 1 sage: P.number_of_linear_extensions() == len(P.linear_extensions()) True """ from sage.combinat.posets.posets import Poset @cached_function def extensions_rec( P ): if P.cardinality() == 1: return 1 exts = 0 for x in P.maximal_elements(): H = P.hasse_diagram() H.delete_vertex( x ) exts += extensions_rec( Poset( H ) ) return exts return extensions_rec( self )