List of tuples without duplicates & repeated values

Given some number nand set of values vals, I want to obtain all the tuples/permutations of size n for the values in vals, but without any repeated tuples. So e.g. n=2 and vals={3,6} should give

 n = 2, vals = {0,1}   --> { {0,0}, {0,1}, {1,1} }  n = 2, vals = {0,1,2} --> { {0,0}, {0,1}, {0,2}, {1,1}, {1,2}, {2,2} }  n = 3, vals = {0,1}   --> { {0,0,0}, {0,0,1}, {0,1,1}, {1,1,1} }  n = 3, vals = {0,1,2} --> { {0,0,0}, {0,0,1}, {0,0,2}, {0,1,1}, {0,1,2}, {0,2,2}, {1,1,1}, {1,1,2}, {1,2,2}, {2,2,2} } 

I’ve tried the following commands:

 n    = 2;  vals = {0, 1};  Tuples[vals, {n}]        (* gives { {0, 0}, {0, 1}, {1, 0}, {1, 1} } *)  Permutations[vals, {n}]  (* gives { {0, 1}, {1, 0} } *)  Subsets[vals, {n}]       (* gives { {0, 1} } *) 

Permutations and Subsets are incomplete. Tuples contains all the right combinations, but also contains duplicates like {0, 1} and {1, 0}. Since I do not care about order, I’d like to remove those.

How do I achieve the behavior of Tuples, but without duplicates?

Partitioning tuples

Given are tuples $ (a_{11},\dots,a_{1k}), (a_{21},\dots,a_{2k}), \dots, (a_{n1},\dots,a_{nk})$ . We want to know if there is a partition of the tuples into two parts, so that for every coordinate $ i=1,\dots,k$ , the sum of each part is equal to the sum of the other part.

Has this problem been studied before? If $ k=1$ , it is of course the famous Partition problem. But I cannot find this generalization under the section “Variants and generalizations” in the Wikipedia page.

Finding Number of Parents from an array of tuples

I am working on a problem and I have a problem finding the individuals with zero parents in a graph of relationships between parents and children over multiple generations. The data is formatted as a list of (parent, child) pairs, where each individual is assigned a unique integer identifier.

Write a function that takes this data as input and returns two collections: one containing all individuals with zero known parents, and one containing all individuals with exactly one known parent. Sample input/output (pseudodata): parentChildPairs = [ (1, 3), (2, 3), (3, 6), (5, 6), (5, 7), (4, 5), (4, 8), (4, 9), (9, 11) ]

Output may be in any order:

findParents(parentChildPairs) =>

[1, 2, 4], Individuals with zero parents

[5, 7, 8, 9, 11] Individuals with exactly one parent

I have included a picture as well as my code for clarityenter image description here

import java.util.*;  public class ParentChildPair {  //get the pairs with just one child...  //idea is to get the child as key and append the parents as the values  static HashMap<Integer, ArrayList<Integer>> childtoParentMap = new HashMap<>(); static ArrayList<Integer> listOfParents = new ArrayList<>();  static ArrayList<Integer> zeroParents = new ArrayList<>(); static ArrayList<Integer> oneParent =   new ArrayList<>();  public static void findParents(int[][] parentChildPairs) {     for(int i = 0; i< parentChildPairs.length; i++)     {         int parent = parentChildPairs[i][0];         int child = parentChildPairs[i][1];          if(childtoParentMap.containsKey(child))         {             listOfParents.add(parent);             childtoParentMap.put(child, listOfParents);         }          else         {             ArrayList<Integer> listOfParents = new ArrayList<>();             listOfParents.add(parent);             childtoParentMap.put(child, listOfParents);         }          //THIS IS MY ATTEMPT OF GETTING THE INDIVIDUALS WITH ZERO PARENTS, IT IS NOT WORKING AS EXPECTED. PLEASE HELP         /*if(!childtoParentMap.containsKey(parent))          {             childtoParentMap.put(parent, null);         }*/     }       for (Map.Entry<Integer,ArrayList<Integer>> entry : childtoParentMap.entrySet())      {           if(entry.getValue() == null)          {              zeroParents.add(entry.getKey());          }            if(entry.getValue().size() == 1)          {              oneParent.add(entry.getKey());          }      }       System.out.println("All individuals with zero known parents: " + zeroParents.toString());      System.out.println("All individuals with one known parent: " + oneParent.toString());     }     public static void main(String[] argv) {      int[][] parentChildPairs = new int[][] {         {1, 3}, {2, 3}, {3, 6}, {5, 6}, {5, 7},         {4, 5}, {4, 8}, {4, 9}, {9, 11}     };      findParents(parentChildPairs);  };  } 

Data Structure for applying transformations upon universe of tuples


I want a data structure which describes a universe of tuples all of length $ n$ , $ U$ . In $ U$ we associate each $ tuple$ with a non-negative value, which we will denote as $ U.count(tuple)$ . If $ U.count(tuple)=0$ , then we consider $ tuple$ to not be in $ U$ . I want to be efficiently update these $ U$ with five operations, some of which involve two fixed constants $ maxVal$ and $ minVal$ . (to clarify, $ maxVal$ and $ minVal$ should not change throughout the process, and should a tuple in $ U$ should never have a value which exceeds $ maxVal$ )

1) append(U,c): yields an updated universe $ U’$ , $ c$ should be below $ maxVal$ . For each tuple $ t$ in $ U$ , make a copy $ t’$ , and append $ c$ to $ t’$ . For each $ t’$ , $ U’.count(t’) = U.count(t)$ .

2) add(U,c,i): yields an updated universe $ U’$ . For each tuple $ t$ in $ U$ , we create a copy $ t’$ , and add $ c$ to $ t'[i]$ . If $ t'[i]<maxVal$ , then then $ t’$ is in $ U’$ and $ U’.count(t’) = U.count(t)$ . Otherwise $ U’.count(t’)=0$ and for our purposes we no longer need to keep track of it, and can exclude it from $ U’$ .

3) merge(U,i,j): yields an updated universe $ U’$ . For each tuple $ t$ in $ U$ , we create a copy $ t’$ , we pop $ t'[j]$ , and add its value to $ t'[i]$ . In this case, there can be multiple tuples $ t$ which correspond to $ t’$ in $ U’$ , thus let us initially say $ U’.count(t’)=0$ and then add to this. Now, if $ t'[i] < maxVal$ , $ U’.count(t’) = U’.count(t’) + U.count(t)$ .

4) finish(U,i): yields an updated universe $ U’$ . For each tuple $ t$ in $ U$ , we make a copy $ t’$ and delete $ t'[i]$ . Again, for the same reasons as in 2, let us initially say $ U’.count(t’) = 0$ . If $ t[i] > minVal$ , then $ t’.count = t’.count + t.count$ . At the end, all $ t’$ with non-zero count are included in $ U’$ .

5) combine(U1,U2): yields an updated universe $ U’$ , $ U_1$ and $ U_2$ should have same length tuples. For each $ t$ in $ U_1 \cup U_2$ , $ U’.count(t) = U_1.count(t) + U_2.count(t)$

My thoughts so far (messy)

If we did this naively, and represented $ U$ as a list of the tuples with non-zero, this would be horribly inefficient. Let’s assume $ U.count(t) \neq 0$ for all $ t$ that don’t exceed $ maxVal$ . Then, with $ maxVal = 10$ , a universe for tuples of length $ 4$ , that’s 10,000 if statements for the add operation…

I think one optimization would to have a tree, where the first level has nodes for each value of $ t[0]$ , and the child of a node are the next element in the tuple. I’d imagine you’d do this by having a list of all your first level nodes. Each node itself, is represented as a tuple of its value, and a list of its valid children, or $ U.count(t)$ for leaves. With add at lower levels, you have much less updates to do, and by ordering children in a fixed way according to their value, and keeping childless nodes as placeholders, your only need to do the validity check once too. Furthermore, to make append efficient, instead of having the levels be consecutive indices, we could make the order arbitrary, describe the tree-level to tuple index conversion with another list. For stuff like combine I am less sure what’s a good way to do things, maybe it would be beneficial to actually sum the counts of shared tuples, but maybe there are a clever cheats or work arounds…

My explicit questions

1a) Is there an efficient data-structure which performs these operations?

1b) Otherwise, are there some general rules of thumb for data structure which are relevant for this problem or my proposed solution?

2) Same as above but for the case where combine is applied to a very large number of universes, instead of just 2.

find internal rhombi from a list of lines defined by point tuples

I have a image like this:

da vinci's "a road in spring"

I have code to extract the lines in the form [x1,x2,y1,y2] Now i need to extract the internal rhombi, one could bruteforce combinations and check for intersections easily, but I was hoping a named, optimal algorithm existed, as the combinatoric explosion would ruin the server,

Any help appreciated

How to filter a list of pairs (tuples) where the tuple doesn’t include any value from another list? – in a more ‘pythonic’ way?

For example.. I have a list of tuples [(1,2),(2,3),(3,4),(4,5),(5,6),(7,8)]

.. and a list of values I want to exclude which are in the format [(2,20),(3,46),(4,918)] The value I want to exclude is the first of the pair. (The meaning of the 20, 46, 918 isn’t important)

So I would want to return a list of tuples that don’t include any of the 2,3, 4 values. Expected result: [(5,6),(7,8)] (because all the others contain one or more of the values 2, 3 or 4)

What I’ve tried:

[p for p in my_list if p[0] not in [v[0] for v in reference_list] and p[1] not in [v[0] for v in reference_list]] 

I’m checking for the first or second value of the pair not being in the list v[0] of the reference list.

It does work but I am looking for a more concise/pythonic way, if any. Ideally extendable (without just adding conditions like p[2] not in list and p[3] not in list and…


Comparing set of tuples? Pareto Front

I need to decide which solution is the best design, in order to do that I need to compare them. Lower energy used and lower weight is better. My initial idea was to order both the fields best to worst and chose based on which one finished higher but whats better 3rd and 2nd, or 1st and 4th?

  1. (Energy Used, Weight)






Diagram Showing the Table

How to efficiently get combinations of array of tuples [int, string] and compare it?

Just wondering if there is a way to run the piece of code below more efficiently. I just started to get acquainted with parallel program and think this might be an answer? But I have no idea how to do it using imap or processes…any help?

This is what the function is doing: it gets two arrays of tuples with 5 items each – hand = [H1,H2,H3,H4,H5] and board = [B1,B2,B3,B4,B5]

What I need to do is check all arrays formed by 2 items from hand and 3 items from board, like combination = [Hn,Hm,Bi,Bj,Bk] (100 combinations in total)

Then I need to compare each one of the combinations against a dictionary to get the combination rank, and then return the best array (best rank) and the rank itself:

def check_hand(hand, board, dictionary_A, dictionary_B):   best_hand = []  first_int = True   for h1 in range (0, 4):   for h2 in range (h1+1, 5):    for b1 in range (0, 3):     for b2 in range (b1+1, 4):      for b3 in range (b2+1, 5):       hand_check = []       hand_check.append(mao[m1])       hand_check.append(mao[m2])       hand_check.append(board[b1])       hand_check.append(board[b2])       hand_check.append(board[b3])       hand_check = sort(hand_check) #Custom sort for my array of objects       hand_ranks = "".join([str(hand_check[0].rank),str(hand_check[1].rank),str(hand_check[2].rank),str(hand_check[3].rank),str(hand_check[4].rank)])        if (hand_check[0].suit == hand_check[1].suit and hand_check[1].suit == hand_check[2].suit and hand_check[2].suit == hand_check[3].suit and hand_check[3].suit == hand_check[4].suit):        control = [dictionary_A[hand_ranks][0],dictionary_A[hand_ranks][1]]       else:        control = [dictionary_B[hand_ranks][0],dictionary_B[hand_ranks][1]]        if first_int:        best_hand = hand_check        rank = control        first_int = False       elif (int(control[0]) > int(rank[0])):        rank = control        best_hand = hand_check              elif (int(control[0]) == int(rank[0])):        if (int(control[1]) > int(rank[1])):                rank = control         best_hand = hand_check         return best_hand, rank[0] 

I need to run this check for 2 million different hands and interact over 1000 times for every hand (Ideally I would run it for at least 100000 times for every hand, for a more statistically accurate result). Any ideas on how to make it more efficient?


For hand = [[‘2′,’s’],[‘5′,’h’],[‘7′,’h’],[‘8′,’c’],[‘T’,s’]] and board = [[‘3′,’s’],[‘3′,’h’],[‘9′,’s’],[‘T’,’c’],[‘6′,s’]]

It compares every combination (2s5h3s3h9s,2s5h3sTc,…., 7hTs3s9s6s,…,8cTs9sTc6s), compares to my dictionaries and returns best_hand = [[‘6′,’s’],[‘7′,’h’],[‘8′,’c’],[‘9′,’s’],[‘T’,’c’]], rank[0] = 5 (from dictionary) which is the best poker hand for this case.

For hand = [[‘8′,’s’],[‘9′,’h’],[‘9′,’c’],[‘A’,’c’],[‘A’,s’]] and board = [[‘7′,’s’],[‘6′,’h’],[‘T’,’s’],[‘T’,’c’],[‘A’,h’]] it will return best_hand = [[‘T’,’s’],[‘T’,’c’],[‘A’,’s’],[‘A’,’h’],[‘A’,’c’]], rank[0] = 7

A cartesian product of tuples in C++17

I would like to write a function that computes a cartesian product of two tuples in C++17 (the tuples can be of type std::tuple or std::pair, or any other type that can be used with std::apply). The tuples can be of different types and sizes, and the resulting std::tuple has to contain all std::pairs of elements, where the first element of a pair is from the first tuple, and the second element is from the second tuple. The function must be suitable for use in a constexpr context.

My approach is to use std::apply to effectively convert a tuple to a parameter pack, and then to recursively apply a generic lambda to it to build the result. Because a lambda cannot be explicitly recursive, I pass a reference to it to itself as an additional parameter self.

#include <functional> #include <tuple> #include <utility>  template<class X, class Y> constexpr auto cartesian_product(const X& tx, const Y& ty) {     return std::apply([&](const auto& ... ys) {         return std::apply([&](const auto& ... xs) {             const auto recursive = [&](                 const auto& self,                 const auto& arg, const auto& ... args)              {                 if constexpr (sizeof...(args) == 0)                     return std::make_tuple(std::make_pair(arg, ys)...);                 else                      return std::tuple_cat(                         std::make_tuple(std::make_pair(arg, ys)...),                          self(self, args...));             };             if constexpr (sizeof...(xs) == 0) return std::make_tuple();             else return recursive(recursive, xs...);         }, tx);     }, ty); }   // Test constexpr auto x = std::make_tuple('a', 2); constexpr auto y = std::make_tuple(true, std::optional<long>{}); constexpr auto result = cartesian_product(x, y);  static_assert(result == std::make_tuple(     std::make_pair('a', true),     std::make_pair('a', std::optional<long>{}),     std::make_pair(2,   true),     std::make_pair(2,   std::optional<long>{}))); 

I would appreciate any comments or suggestions how to simplify or improve this code.