Why can’t we use list as keys in python but we can use tuple as a key in python dictionaries.
Tag: tuples
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 clarity
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
Problem
I want a data structure which describes a universe of tuples all of length $ n$ , $ U$ . In $ U$ we associate each $ tuple$ with a nonnegative 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 nonzero 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 nonzero, 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 treelevel 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 datastructure 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:
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…
Thanks!
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?

(Energy Used, Weight)
(30,20)
(50,30)
(10,40)
(20,50)
(40,10)
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?
Examples:
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::pair
s 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.
Faithful group actions on tuples from algebraic structures
So I am looking for examples of the following phenomenon.
Suppose that $ V$ is a variety with a computable equational theory which is not locally finite. Suppose that $ G$ is an infinite finitely presented group generated by elements $ s_{1},\dots,s_{k}$ . Suppose furthermore that $ G$ has a polynomial time computable normal form. In other words, there is a function $ f:\{w_{1},\dots,w_{k},w^{1}_{1},\dots,w_{k}^{1}\}^{*}\rightarrow\mathbb{N}$ computable in polynomial time such that if $ d_{i},e_{i}\in\{1,1\},a_{i},b_{i}\in\{1,\dots,k\}$ for each $ i$ , then $ f(w_{a_{1}}^{d_{1}}\dots w_{a_{u}}^{d_{u}})=f(w_{b_{1}}^{e_{1}}\dots w_{b_{v}}^{e_{v}})$ if and only if $ s_{a_{1}}^{d_{1}}\dots s_{a_{u}}^{d_{u}}=s_{b_{1}}^{e_{1}}\dots s_{b_{v}}^{e_{v}}$ . Suppose that there is some $ n$ along with two matrices of terms $ $ (t_{i,j}(x_{1},…,x_{n}))_{1\leq i\leq n,1\leq j\leq k},(t^{*}_{i,j}(x_{1},…,x_{n}))_{1\leq i\leq n,1\leq j\leq k}.$ $ These terms come from the variety $ V$ . Then whenever $ X\in V,$ define actions of $ \{w_{1},\dots,w_{k},w^{1}_{1},\dots,w_{k}^{1}\}^{*}$ on $ X^{n}$ $ $ (x_{1},\dots,x_{n})\cdot w_{j}=(t_{1,j}(x_{1},\dots,x_{n}),\dots,t_{n,j}(x_{1},\dots,x_{n}))$ $ and $ $ (x_{1},\dots,x_{n})\cdot w_{j}^{1}=(t_{1,j}^{*}(x_{1},\dots,x_{n}),\dots,t_{n,j}^{*}(x_{1},\dots,x_{n})).$ $
Then the variety $ V$ satisfies the identities $ $ (x_{1},\dots,x_{n})\cdot w_{a_{1}}^{d_{1}}\dots w_{a_{u}}^{d_{u}}=(x_{1},\dots,x_{n})\cdot w_{b_{1}}^{e_{1}}\dots w_{b_{v}}^{e_{v}}$ $ if and only if $ s_{a_{1}}^{d_{1}}\dots s_{a_{u}}^{d_{u}}=s_{b_{1}}^{e_{1}}\dots s_{b_{v}}^{e_{v}}$ , and the equational theory of the variety $ V$ is axiomatized by the identities of the form $ $ (x_{1},\dots,x_{n})\cdot w_{a_{1}}^{d_{1}}\dots w_{a_{u}}^{d_{u}}=(x_{1},\dots,x_{n})\cdot w_{b_{1}}^{e_{1}}\dots w_{b_{v}}^{e_{v}}$ $ where $ d_{i},e_{i}\in\{1,1\},a_{i},b_{i}\in\{1,\dots,k\}$ for each $ i.$
In this case, the group $ G$ acts on $ X^{n}$ for each $ X\in V$ by letting $ $ (x_{1},…,x_{n})\cdot s_{a_{1}}^{d_{1}}\dots s_{a_{u}}^{d_{u}}=(x_{1},…,x_{n})\cdot w_{a_{1}}^{d_{1}}\dots w_{a_{u}}^{d_{u}}$ $ where $ d_{i},e_{i}\in\{1,1\},a_{i},b_{i}\in\{1,\dots,k\}$ for each $ i.$
Examples
Example 1: The symmetry group $ S_{k}$ . Suppose that $ \tau_{i}=(i,i+1)$ . Then we set $ $ (x_{1},\dots,x_{k})\tau_{i}=(x_{1},\dots,x_{i1},x_{i+1},x_{i},x_{i+2},\dots,x_{k}).$ $
Example 2: The braid group $ B_{k}$ acting on racks and quandles. Suppose that $ (X,*)$ is a rack or a quandle (Let us use leftdistributivity $ x*(y*z)=(x*y)*(x*z)$ ). Then define $ $ (x_{1},\dots,x_{n})\cdot\sigma_{i}=(x_{1},\dots,x_{i1},x_{i}*x_{i+1},x_{i},x_{i+2},\dots,x_{n}).$ $
Example 3: $ \mathrm{Aut}(F_{k})$ acting on tuples from groups.
Example 4: Finite direct products of groups.
In the case where the group $ G$ is finite or though the conditions I have listed out are otherwise not technically satisfied (for example by the infinite strand braid group $ B_{\infty}$ on $ X^{\mathbb{N}}$ for each rack $ X$ ), feel free to give an answer anyways if you feel the answer is still interesting yet does not stray from the spirit of the question too much.
driver.find_elements does not work with tuples argument
the tuples argument is not working
enter code here
options = Options() options.add_argument(“–headless”)
dic = {‘Onix’: ‘bid=1&app=20&sop=nta_174451.1_kmm_0.1_mar_5.1_mod_2428.1_est_SP.1_cid_9668.1_rai_50.1_esc_2.1_sta_1.1_&pas=1&lis=0&’, ‘HB20’: ‘bid=3&app=20&sop=nta_174451.1_kmm_0.1_mar_17.1_mod_2398.1_est_SP.1_cid_9668.1_rai_50.1_esc_2.1_sta_1.1_&pas=1&lis=0&’, ‘Ka’: ‘bid=4&app=20&sop=nta_174451.1_kmm_0.1_mar_15.1_mod_287.1_est_SP.1_cid_9668.1_rai_50.1_esc_2.1_sta_1.1_&pas=1&lis=0&’, ‘Gol’: ‘bid=5&app=20&sop=nta_174451.1_kmm_0.1_mar_36.1_mod_480.1_est_SP.1_cid_9668.1_rai_50.1_esc_2.1_sta_1.1_&pas=1&lis=0&’, ‘Prisma’: ‘bid=1&app=20&sop=nta_174451.1_kmm_0.1_mar_5.1_mod_902.1_est_SP.1_cid_9668.1_esc_1.1_sta_1.1_&pas=1&lis=0&’, ‘Polo’: ‘bid=2&app=20&sop=nta_174451.1_kmm_0.1_mar_36.1_mod_491.1_est_SP.1_cid_9668.1_rai_50.1_esc_2.1_sta_1.1_&pas=1&lis=0&’, ‘Kwid’: ‘bid=3&app=20&sop=nta_174451.1_kmm_0.1_mar_31.1_mod_2727.1_est_SP.1_cid_9668.1_rai_50.1_esc_2.1_sta_1.1_&pas=1&lis=0&’, ‘Argo’: ‘bid=4&app=20&sop=nta_174451.1_kmm_0.1_mar_14.1_mod_2723.1_est_SP.1_cid_9668.1_rai_50.1_esc_2.1_sta_1.1_&pas=1&lis=0&’, ‘Compass’:’bid=5&app=20&sop=nta_174451.1_kmm_0.1_mar_19.1_mod_2340.1_est_SP.1_cid_9668.1_rai_50.1_esc_2.1_sta_1.1_&pas=1&lis=0&’, ‘Corolla’: ‘bid=6&app=20&sop=nta_174451.1_kmm_0.1_mar_35.1_mod_468.1_est_SP.1_cid_9668.1_rai_50.1_esc_2.1_sta_1.1_&pas=1&lis=0&’, ‘Sandero’:’bid=7&app=20&sop=nta_174451.1_kmm_0.1_mar_31.1_mod_919.1_est_SP.1_cid_9668.1_rai_50.1_esc_2.1_sta_1.1_&pas=1&lis=0&’, ‘Mobi’:’bid=8&app=20&sop=nta_174451.1_kmm_0.1_mar_14.1_mod_2679.1_est_SP.1_cid_9668.1_rai_50.1_esc_2.1_sta_1.1_&pas=1&lis=0&’, ‘Creta’:’bid=9&app=20&sop=nta_174451.1_kmm_0.1_mar_17.1_mod_2714.1_est_SP.1_cid_9668.1_rai_50.1_esc_2.1_sta_1.1_&pas=1&lis=0&’, ‘HRV’:’bid=10&app=20&sop=nta_174451.1_kmm_0.1_mar_16.1_mod_2627.1_est_SP.1_cid_9668.1_rai_50.1_esc_2.1_sta_1.1_&pas=1&lis=0&’, ‘Kicks’: ‘bid=11&app=20&sop=nta_174451.1_kmm_0.1_mar_28.1_mod_2696.1_est_SP.1_cid_9668.1_rai_50.1_esc_2.1_sta_1.1_&pas=1&lis=0&’, ‘Renegade’:’bid=12&app=20&sop=nta_174451.1_kmm_0.1_mar_19.1_mod_2628.1_est_SP.1_cid_9668.1_rai_50.1_esc_2.1_sta_1.1_&pas=1&lis=0&’, ‘Virtus’:’bid=13&app=20&sop=nta_174451.1_kmm_0.1_mar_36.1_mod_2750.1_est_SP.1_cid_9668.1_rai_50.1_esc_2.1_sta_1.1_&pas=1&lis=0&’, ‘Fox’:’bid=16&app=20&sop=nta_174451.1_kmm_0.1_mar_36.1_mod_478.1_est_SP.1_cid_9668.1_rai_50.1_esc_2.1_sta_1.1_&pas=1&lis=0&’, ‘Ka Sedan’:’bid=17&app=20&sop=nta_174451.1_kmm_0.1_mar_15.1_mod_2547.1_est_SP.1_cid_9668.1_rai_50.1_esc_2.1_sta_1.1_&pas=1&lis=0&’, ‘EcoSport’:’bid=18&app=20&sop=nta_174451.1_kmm_0.1_mar_15.1_mod_607.1_est_SP.1_cid_9668.1_rai_50.1_esc_2.1_sta_1.1_&pas=1&lis=0&’}
def icarros(carro): tuples= [] for i in range(1, 100): driver = webdriver.Chrome(r’J:\Eco_Asset\EEE SAM\Python\chromedriver_win322\chromedriver.exe’, options=options) driver.set_script_timeout(10000) driver.set_page_load_timeout(10000)
url = 'https://www.icarros.com.br/ache/listaanuncios.jsp?' + dic[carro] + 'pag=%s&ord=16' % i driver.get(str(url)) f = '//*[@id="conteudoLista"]/div[3]/div[2]/div[4]/div[2]/ul' try: driver.find_element_by_xpath(f) for (x,y) in zip(driver.find_elements_by_css_selector('h3.direita.preco_anuncio'), driver.find_elements_by_css_selector('h2.esquerda.titulo_anuncio')): a = (y.get_attribute('innerHTML').replace('<span>', '').replace('</span>', '').strip(), x.get_attribute('innerHTML')) print(a) tuples.append(a) WebDriverWait(driver, 2000).until(EC.element_to_be_clickable((By.XPATH, f))) except NoSuchElementException: break driver.close() df = pd.DataFrame(tuples, columns = [carro, 'Preço']) df['Data'] = datetime.date.today().isoformat() df = df.set_index(['Data']) return df
df = pd.DataFrame() for i in dic: x = icarros(i) df = pd.concat([df, x], axis=1)