string manipulation – P=QRS decomposition of given list -2 -unordered list

This is an extended version of my previous post, $P=QRS$ decomposition of given list

Based on the answer and comment of @Bill,

Form all permutations of P. Form Q as the first element of each of those, R as the second element and S all the rest of each perm. Then do this with R of length 2. And then of length 3. And … until you are down to S of length 1. Now start over with Q of length 2, etc, etc, etc.

for length $3$, I have done this via

A3 = Permutations({a1, a2, a3})
For(i = 1, i <= Length(A3), i++,
P(i) = Partition(A3((i)), 1));
 
For(i = 1, i <= Length(A3), i++,
 Q(i) = P(i)((1));
 R(i) = P(i)((2));
 S(i) = P(i)((3)); );
Table(Flatten({Q(i), R(i), S(i)}), {i, 1, Length(A3)})

It looks okay, but I am having trouble with length 4. With the same instruction I did

A4 = Permutations({a1, a2, a3, a4})
Length(A4)
For(i = 1, i <= Length(A4), i++,
 P(i) = Partition(A4((i)), 1)
 );

(*2+1+1*)
For(i = 1, i <= Length(A4), i++,
 Q1(i) = Flatten({P(i)((1)), P(i)((2))});
 R1(i) = P(i)((3));
 S1(i) = P(i)((4));
  )
(*1+2+1*)
 For(i = 1, i <= Length(A4), i++,
 Q2(i) = P(i)((1));
 R2(i) = Flatten({P(i)((2)), P(i)((3))});
 S2(i) = P(i)((4));
  )
(*1+1+2*)
 For(i = 1, i <= Length(A4), i++,
 Q3(i) = P(i)((1));
 R3(i) = P(i)((2));
 S3(i) = Flatten({P(i)((3)), P(i)((4))});
 )

But here the size does not agree with what I expected; For length $4$ case there is three choices to divide, $(1,1,2), (1,2,1),(2,1,1)$ and by symmetry, for each of them there are $ 12$ of them so the total is $36$. But here individuals have $24$ and thus $24times 3=72$.

For example, ${1,2,3,4}$ with $(1,1,2)$ decomposition, we have $(1,2,34),(1,3,24),(1,4,23), (2,1,34),(2,3,14),(2,4,13),(3,1,24),(3,2,14),(3,4,12),(4,1,23),(4,2,13),(4,3,12)$ 12 cases (One can think of this first by chossing $2$ elements among $4$ and multiplying the degeneracy $2$)

For $P=QR$ decomposition of an unordered set, the subset is enough for whole possible cases, but in this case, after dividing into $P=QR$ and $R=R’S$, the total size should be increased, and there are some problems for injecting more possible lists into the first partitions.

Before this setup, I just plugging all the possible cases of length $4$ individually, but I realized this is very inefficient and even produces typos(human error) for length $5$ and more than length $5$ cases.

Besides permutations, I tried to formulate similar things with partitions command but I realized the assign function of partition only produces partitions up to its length, not partition into three pieces or more than three. i.e., as a manual says

 Partition({a, b, c, d, e, f}, 3, 1)

produces sequences of length 3 with offset 1…

Any ideas or explicit examples are welcome!

design – Unordered command arguments in help menu

I noticed that many popular tools, e.g., git, bash commands, do not arrange the command arguments in alphabetical order in their manuals or help menus.

For example:

$ git blame -h
usage: git blame (<options>) (<rev-opts>) (<rev>) (--) <file>

    <rev-opts> are documented in git-rev-list(1)

    --incremental         show blame entries as we find them, incrementally
    -b                    do not show object names of boundary commits (Default: off)
    --root                do not treat root commits as boundaries (Default: off)
    --show-stats          show work cost statistics
    --progress            force progress reporting
    --score-debug         show output score for blame entries
    -f, --show-name       show original filename (Default: auto)
    -n, --show-number     show original linenumber (Default: off)
    -p, --porcelain       show in a format designed for machine consumption
    --line-porcelain      show porcelain format with per-line commit information
    -c                    use the same output mode as git-annotate (Default: off)
    -t                    show raw timestamp (Default: off)
    -l                    show long commit SHA1 (Default: off)
    -s                    suppress author name and timestamp (Default: off)
    -e, --show-email      show author email instead of name (Default: off)
    -w                    ignore whitespace differences
    --ignore-rev <rev>    ignore <rev> when blaming
    --ignore-revs-file <file>
                          ignore revisions from <file>
    --color-lines         color redundant metadata from previous line differently
    --color-by-age        color lines by age
    --minimal             spend extra cycles to find better match
    -S <file>             use revisions from <file> instead of calling git-rev-list
    --contents <file>     use <file>'s contents as the final image
    -C(<score>)           find line copies within and across files
    -M(<score>)           find line movements within and across files
    -L <range>            process only line range <start>,<end> or function :<funcname>
    --abbrev(=<n>)        use <n> digits to display object names

Why is that so? Won’t it improve readability and search if the arguments were sorted? Is it an issue of back words compatibility with previous releases? Or lack of resources, as a result very low task priority?

python – Inheritance vs composition: How would you implement an “unordered list”? Subclass of list, or composition?

This came up at work and left me thinking about the best way to model this:

In Python, we have the built-in list container, which is a mutable sequence. Equality between two lists is defined as equality of all items in the list, in their respective positions.

Now a colleague felt the need to define a type that’s a list for all practical purposes, except that two lists should be considered equal if they contain the same elements, in the same quantities, but in arbitrary order. Basically,

unordered_list_1 = UnorderedList((1,2,3))
unordered_list_2 = UnorderedList((3,2,1))

unordered_list_1 == unordered_list_2 # True!

The colleague solved this by inheriting from list and overriding the __eq__ special method:

class UnorderedList(list):
  def __eq__(self, other):
    if isinstance(other, UnorderedList):
      return ordered(self) == ordered(other)
    else:
      return NotImplemented

In this form it runs into a gotcha, because the builtin python types such as list take some shortcuts with their special methods; the not-equal __ne__ special method does not just fall back onto the __eq__ special method, so you get the funny scenario where two of these unordered lists can both be equal and not equal.

I suggested inheriting from UserList instead, which is meant to be subclassed, or maybe from one of the collections.abc abstract base classes. Another colleague chimed in with the familiar “Favor composition over inheritance” advice.

I feel that composition in this case would lead to a lot of boilerplate delegation code:

class UnorderedListUsingDelegation:
  def __init__(self):
    self._list = list()

  def __eq__(self, other):
    if isinstance(other, UnorderedListUsingDelegation):
      return ordered(self._list) == ordered(self.other._list)
    else:
      return NotImplemented

  def append(self, item):
    self._list.append(item)

  # Basically def every method implemented by class list and write delegation code for it:
  # pop, push, extend, __getitem__, __setitem__ and so on

So from that consideration, I feel like inheritance is exactly right here: A teeny tiny specialization of behavior.

But on the other hand: Is the UnorderedList actually substitutable for the list class? Not so sure here. If you do “normal” list operations, then you shouldn’t notice whether you are using an instance of the list class or of the UnorderedList class. Inserting and retrieving of elements works just fine. On the other hand, you might get unexpected behavior when comparing lists:

list1 = UnorderedList()
list2 = UnorderedList()

list1.append(1)
list2.append(3)

list1 == list2 # False

list1.append(2)
list2.append(2)

list1 == list2 # False

list1.append(3)
list2.append(3)

list1 == list2 # True!

I guess what I’m after is some clarity on how broadly or narrowly the Liskov substitution principle should be applied. Or maybe the solution is something altogether different. Maybe we shouldn’t put such a “hack” into the __eq__ special method and rather be explicit about what we’re doing, by writing a function like

def sorted_equal(a, b):
  return sorted(a) == sorted(b)

I assume the colleague is working with some framework that expects to be working with list objects but wants to inject this special way of comparing lists.

java – Given an unordered symbol table(array based) Is there an advantage to using a contains method that returns the index?

I am working on an assignment and was curious about a potential real world application. Would it be more efficient to use a contains method that returns the index of the key or -1 if not found. This I imagine would allow the programmer the ability to save double calls to get and contains within a method. Both methods have O(n) time complexity worst case. Is there a reason not to do it? The only reason why I could imagine not doing so is because it could confuse the client.

performance – Wrote My own data structure. Mixture of a doubly linked list & unordered map C++

I decided to make my own data structure. I did this because I wanted a data structure that is a queue but has o(1) time on lookup.

    template <class Object>
class ObjectQueue;
template <class Object>
class ObjectQueueNode: private NonCopyable
{
    friend class ObjectQueue<Object>;
public:
    ObjectQueueNode(const glm::ivec3& position)
        : position(position),
        previous(nullptr),
        next(nullptr)
    {}
    ObjectQueueNode(ObjectQueueNode&& orig) noexcept
        : position(orig.position),
        previous(orig.previous),
        next(orig.next)
    {
        orig.previous = nullptr;
        orig.next = nullptr;
    }
    ObjectQueueNode& operator=(ObjectQueueNode&& orig) noexcept
    {
        position = orig.position;
        previous = orig.previous;
        next = orig.next;

        orig.previous = nullptr;
        orig.next = nullptr;

        return *this;
    }

    const glm::ivec3& getPosition() const
    {
        return position;
    }

private:
    glm::ivec3 position;
    Object* previous;
    Object* next;
};

struct PositionNode : public ObjectQueueNode<PositionNode>
{
    PositionNode(const glm::ivec3& position)
        : ObjectQueueNode(position)
    {}
};

template <class Object>
class ObjectQueue : private NonCopyable, private NonMovable
{
public:
    ObjectQueue()
        : m_initialObjectAdded(nullptr),
        m_recentObjectAdded(nullptr),
        m_container()
    {}

    void add(Object&& newObject)
    {
        glm::ivec3 position = newObject.position;
        if (m_container.empty())
        {
            assert(!m_initialObjectAdded && !m_recentObjectAdded);
            Object& addedObject = m_container.emplace(std::piecewise_construct,
                std::forward_as_tuple(position),
                std::forward_as_tuple(std::move(newObject))).first->second;

            addedObject.previous = nullptr;
            m_initialObjectAdded = &addedObject;
            m_recentObjectAdded = &addedObject;
        }
        else if (m_container.size() == 1)
        {
            assert(m_initialObjectAdded && m_recentObjectAdded);
            Object& addedObject = m_container.emplace(std::piecewise_construct,
                std::forward_as_tuple(position),
                std::forward_as_tuple(std::move(newObject))).first->second;

            addedObject.previous = m_initialObjectAdded;
            m_initialObjectAdded->next = &addedObject;
            m_recentObjectAdded = &addedObject;
        }
        else if (m_container.size() > 1)
        {
            assert(m_initialObjectAdded && m_recentObjectAdded);
            Object& addedObject = m_container.emplace(std::piecewise_construct,
                std::forward_as_tuple(position),
                std::forward_as_tuple(std::move(newObject))).first->second;

            addedObject.previous = m_recentObjectAdded;
            m_recentObjectAdded->next = &addedObject;
            m_recentObjectAdded = &addedObject;
        }
    }

    bool contains(const glm::ivec3& position) const
    {
        return m_container.find(position) != m_container.cend();
    }

    bool isEmpty() const
    {
        return m_container.empty();
    }

    Object* next(Object* object)
    {
        assert(m_initialObjectAdded && m_recentObjectAdded && !m_container.empty());
        if (object)
        {
            return object->next;
        }
        else
        {
            return nullptr;
        }
    }

    Object& front()
    {
        assert(m_initialObjectAdded && m_recentObjectAdded && !m_container.empty());

        auto iter = m_container.find(m_initialObjectAdded->position);

        assert(iter != m_container.end());
        return iter->second;
    }

    void pop()
    {
        assert(m_initialObjectAdded && m_recentObjectAdded && !m_container.empty());

        auto iter = m_container.find(m_initialObjectAdded->position);
        assert(iter != m_container.end());

        if (m_container.size() == 1)
        {
            assert(m_initialObjectAdded == m_recentObjectAdded);
            m_initialObjectAdded = nullptr;
            m_recentObjectAdded = nullptr;

        }
        else if (m_container.size() > 1)
        {
            assert(m_initialObjectAdded->next);
            m_initialObjectAdded = m_initialObjectAdded->next;
            m_initialObjectAdded->previous = nullptr;
        }

        m_container.erase(iter);
    }

    Object* remove(const glm::ivec3& position)
    {
        auto iter = m_container.find(position);
        if (iter != m_container.end())
        {
            assert(m_initialObjectAdded && m_recentObjectAdded);
            Object* previousObject = iter->second.previous;
            Object* nextObject = iter->second.next;

            //Top
            if (!nextObject && previousObject)
            {
                m_recentObjectAdded = previousObject;
                m_recentObjectAdded->next = nullptr;
                previousObject->next = nullptr;
            }
            //Bottom
            else if (!previousObject && nextObject)
            {
                m_initialObjectAdded = nextObject;
                m_initialObjectAdded->previous = nullptr;
                nextObject->previous = nullptr;
            }
            //Inbetween
            else if (previousObject && nextObject)
            {
                previousObject->next = nextObject;
                nextObject->previous = previousObject;
            }
            else
            {
                assert(m_container.size() == 1);
                m_initialObjectAdded = nullptr;
                m_recentObjectAdded = nullptr;
            }

            m_container.erase(iter);
            return nextObject;
        }

        return nullptr;
    }

private:
    Object* m_initialObjectAdded;
    Object* m_recentObjectAdded;

    std::unordered_map<glm::ivec3, Object> m_container;
};

replacing a sup-partition (unordered list; multiset)

I am working on a bijection for integer partitions and would appreciate help with two steps.

First, I want to replace each occurrence of (4, 2, 1, 1) with (3, 3, 2). One complication is that the 4, 2, 1, and 1 need not be adjacent. For example, the input

{{4, 4, 2, 2, 1, 1, 1}, {4, 4, 2, 2, 2, 1}}

should lead to the output

{{4, 3, 3, 2, 2, 1}, {4, 4, 2, 2, 2, 1}}

since the first partition does include (4, 2, 1, 1), even with the extra 2, and the second does not.

Second, in a later step, I need a 2 and all ones, suppose there are $k$ of them, to be changed to the single number $k+2$, e.g., input

{{5, 2, 1, 1}, {4, 3, 1, 1}, {2, 2, 2, 1, 1, 1}}

should lead to the output

{{5, 4}, {5, 2, 2}, {4, 3, 1, 1}}.

php – How do I convert HTML headings (h2, h3, h4) to nested unordered lists or multi-dimensional arrays?

Input array with HTML headings from a WordPress post

$headings = array(
    '(0)' => '

Number One

', '(1)' => '

Number Two

', '(2)' => '

Number Three

', '(3)' => '

Number Four

', '(4)' => '

Number Five

', '(5)' => '

Number Six

', '(6)' => '

Number Seven

', '(7)' =>'

Number Eight

' );

Now I want to generate a structure in a nested unordered list.

I don't want to use a regular expression. Is there an easy way to do this with Simple HTML DOM Parser? Or a trick? It would be okay to get a multi-dimensional array as a starting point for generating the unordered list.

output

  • Number One
  • Number Two
  • Number Three
    • Number Four
  • Number Five
  • Number Five
    • Number Six
      • Number Seven
  • Number Eight
  • Rendered HTML looks like this:

    • Number one
    • number two
    • number three
    • number five
    • number five
    • Number eight

    php – Function to run through an unordered list of user-defined taxonomy terms

    I have created a function that generates one

      my WordPress custom taxonomy terms, ad parent > child > second child Heritage. Functionally, it works perfectly and replaces my old hard-coded menu.

      The problem is that I'm inexperienced and recognize it as an ugly, inefficient feature, but couldn't figure out how to improve it. I tried & # 39; While () & # 39; – Use loops to simplify things, but didn't get stuck. Could someone help me understand how I can improve this. The final output (including CSS and jQuery to reduce menu items that are disabled) is included below.

      //Display Navigation Menu
      
      function taxonomy_nav(){
      
        //Get Parent Terms
        $getParents = (
          'taxonomy'     => 'kernal_category',
          'parent'        => 0,
          'number'        => 0,
          'hide_empty'    => false  
        );
      
        //Assign parent terms to variable
        $parent_terms = get_terms( $getParents );  
      
        //Loop through parent terms
        foreach ( $parent_terms as $parent_term ) {   
      
          //Store children terms 
          $childrenCheck = get_term_children( $parent_term->term_id, $parent_term->taxonomy );
      
          //If parent term has children...
          if ( ! is_wp_error( $childrenCheck ) && ! empty ( $childrenCheck ) ) {
      
            //Output parent term and start new children list
            echo '
    • '. $parent_term->name.''; echo '
        '; //Loop through child items and output name foreach ( get_terms( 'kernal_category', array( 'hide_empty' => false, 'parent' => $parent_term->term_id ) ) as $child_term) { //Check if children have children $secondChildrenCheck = get_term_children( $child_term->term_id, $child_term->taxonomy ); //Generate list for second children if ( ! is_wp_error( $secondChildrenCheck ) && ! empty( $secondChildrenCheck ) ) { echo '
      • ' . $child_term->name.''; echo '
          '; //If child has child, look through child foreach ( get_terms( 'kernal_category', array( 'hide_empty' => false, 'parent' => $child_term->term_id ) ) as $second_child_term) { echo '
        • '.$second_child_term->name . '
        • '; } echo '
        '; echo '
      • '; } else { echo '
      • '. $child_term->name.'
      • '; } } echo '
      '; echo '
    • '; } else { echo '
    • '. $parent_term->name.'
    • '; } }

      Final list =

    Functional data structure to be completed quickly and deleted in an unordered manner

    I'm looking for a working data structure that would work in this role.

    Adding elements to the structure is common. Removing elements from the structure happens as often as adding them, but I have no way of knowing the order in which the deletion occurs. In the long run, adding is synonymous with removal. Rarely do I need all the elements currently in the tree

    I thought about using a queue, but removing it from a queue out of order is expensive.

    c # – Unordered enumerators in an ObjectValue implementation

    I was just about to shamelessly copy this implementation Value Object In one of my projects, I have just noticed that the enumerators are not being disposed of and I wonder if this could actually be a problem.

    using System.Collections.Generic;
    using System.Linq;
    
    Namespace Microsoft.eShopOnContainers.Services.Ordering.Domain.SeedWork
    {
    public abstract class ValueObject
    {
    protected static bool EqualOperator (ValueObject left, ValueObject right)
    {
    if (ReferenceEquals (left, null) ^ ReferenceEquals (right, null))
    {
    return it incorrectly;
    }
    
    Return ReferenceEquals (left, null) || left. Equals (right);
    }
    
    protected static bool NotEqualOperator (ValueObject left, ValueObject right)
    {
    back! EqualOperator (left, right);
    }
    
    protected abstract IEnumerable GetAtomicValues ​​();
    
    public override bool Equals (object obj)
    {
    if (obj == null || obj.GetType ()! = GetType ())
    {
    return it incorrectly;
    }
    
    var other = (ValueObject) obj;
    
    // No use or disposal called?!?
    var thisValues ​​= GetAtomicValues ​​(). GetEnumerator ();
    var otherValues ​​= other.GetAtomicValues ​​(). GetEnumerator ();
    
    while (thisValues.MoveNext () && otherValues.MoveNext ())
    {
    if (ReferenceEquals (thisValues.Current, null) ^ ReferenceEquals (otherValues.Current, null))
    {
    return it incorrectly;
    }
    if (thisValues.Current! = null &&! thisValues.Current.Equals (otherValues.Current))
    {
    return it incorrectly;
    }
    }
    return! thisValues.MoveNext () &&! otherValues.MoveNext ();
    }
    
    public override int GetHashCode ()
    {
    return GetAtomicValues ​​()
    .Select (x => x! = Zero? X.GetHashCode (): 0)
    Aggregates ((x, y) => x ^ y);
    }
    
    public ValueObject GetCopy ()
    {
    return MemberwiseClone () as ValueObject;
    }
    }
    }
    
    

    And instead the Equal Method above should be revised as:

    public override bool Equals (object obj)
    {
    if (obj == null || obj.GetType ()! = GetType ())
    {
    return it incorrectly;
    }
    
    var other = (ValueObject) obj;
    
    using (var thisValues ​​= GetAtomicValues ​​(). GetEnumerator ())
    {
    using (var otherValues ​​= other.GetAtomicValues ​​(). GetEnumerator ())
    {
    while (thisValues.MoveNext () && otherValues.MoveNext ())
    {
    if (ReferenceEquals (thisValues.Current, null) ^ ReferenceEquals (otherValues.Current, null))
    {
    return it incorrectly;
    }
    if (thisValues.Current! = null &&! thisValues.Current.Equals (otherValues.Current))
    {
    return it incorrectly;
    }
    }
    
    return! thisValues.MoveNext () &&! otherValues.MoveNext ();
    }
    }
    }
    

    If there is not something I do not know about Enumerator and eliminate it, I've found the defect With, To dispose () Dangerous, am I worried about nothing too much?