3,144 questions
0
votes
1
answer
146
views
Advanced combinatorics in Python: binom(n,2) subsets of binom(n,3) combinations without repetition
I have a list d_n of n integers and the results Z_klm of a function fun(dk, dl, dm) for all binom(n, 3) combinations without repetition (k, l, m) out of d_n indices.
Now, for all binom(n, 2) ...
4
votes
2
answers
84
views
Is there a way to use itertools with conditions for sets and arbitrary length?
I'm trying to create a list of subsets that add to a particular sum (e.g. 12), but with a limit on the occurrences of some of the terms.
The base set to iterate on is {1,2,3,4,5,6,7,8}. I'm trying to ...
3
votes
4
answers
206
views
Cartesian product for both keys and values of a dictionary?
I need to get the Cartesian product of a dictionary {str: Fraction} with itself, but currently need to "loop" through the dict twice, once for the keys and once for the values.
The ...
2
votes
2
answers
228
views
How can I remove only consecutive duplicate elements from a larger list in Python? [duplicate]
I have a list of elements where I want to remove only consecutive duplicates, not all duplicates.
For example:
data = [1, 1, 2, 2, 2, 3, 1, 1]
I want to get:
[1, 2, 3, 1]
This is different from using ...
5
votes
2
answers
163
views
Performance of list.extend slice vs islice
It seems that even when islice would theoretically be better, in practice, it is slower than just using slice. So I am a bit puzzled by the difference in performance between the usage of slice and ...
1
vote
1
answer
207
views
Create all possible outcomes from numpy matrices that show disjoints and subsets
Let's assume there is an event and within this event there are multiple outcomes that can co-exist.
An example would be a tennis game where A plays against B and B serves. A couple of possible ...
2
votes
1
answer
180
views
How to create possible sets of n numbers from m-sized prime number list?
Input: a list of m prime numbers (with possible repetition), and integers n and t.
Output: all sets of n numbers, where each set is formed by partitioning the input into n parts, and taking the ...
3
votes
2
answers
110
views
What's the fastest way of skipping tuples with a certain structure in a itertool product?
I have to process a huge number of tuples made by k integers, each ranging from 1 to Max_k.
Each Max can be different.
I need to skip the tuples where an element has reached is max value, in that case ...
1
vote
0
answers
67
views
How do I use a custom mapping (sort) on my itertools for loop so that I can print specific strings first?
I'm using python itertools specifically to generate combinations of integer strings. I have already created the loop that will loop through the combinations one at a time. I just need someone to help ...
-1
votes
1
answer
37
views
Tupe video clips list, the other matching durations. Itertools can find triplets that total 90 sec from duration list. Want to print clip names
I can get the triplets with iteration tools in durations list but I want to get matching clips from spots list. Tried to marry two list but dont know how to apply iteration combo on one part of the ...
1
vote
2
answers
61
views
Dealing with `StopIteration` return from a next() call in Python
I'm using the below to skip a group of records when a certain condition is met:
if (condition met):
...
[next(it) for x in range(19)]
Where it is an itertuples object created to speed up ...
-2
votes
2
answers
77
views
Python itertools product aborting
When running the code below, python aborts and closes the python prompt:
>>> import itertools
>>> nComb = 2
>>> t = range(nComb)
>>> combs = list(itertools.product(...
1
vote
1
answer
98
views
Type hint for itertools.product doesn't know length of elements
I am adding type hints to an old code of mine. However, I find with a "problem" I don't know how to solve. I have a function that looks like:
def f(x: tuple[tuple[int, int], ...]):
...
...
2
votes
0
answers
134
views
Efficiently Handling Large Combinations in Polars Without Overloading RAM
I have a list of n values (in my case, n=19), and I want to generate all possible combinations of these values. My goal is to use each combination as a filter for a Polars DataFrame, iterate over the ...
1
vote
1
answer
117
views
Is there an iterator in Python that gives the product but omits permutations of the classes itself?
Assume that I want to assign a color to 5 different balls and have 3 colors r,b and g. I would like to iterate over all these combinations. Preferably I would want to omit combinations that are equal ...
2
votes
1
answer
80
views
itertools.product in dataframe
Inputs:
arr1 = ["A","B"]
arr2 = [[1,2],[3,4,5]]
Expected output:
short_list
long_list
0
A
1
1
A
2
2
B
3
3
B
4
4
B
5
Current output:
short_list
long_list
0
A
[1, 2]
1
A
[3, 4, 5]...
0
votes
0
answers
26
views
Iterate over dependent iterators together [duplicate]
So here is my scenario:
def gen1(a):
for item in a: ...
0
votes
1
answer
80
views
Python Flask App Freezes with Large Data: Seeking Optimization Advice
I'm developing a Python Flask application to find combinations of numbers from dataset that sum up to a target value. The app works fine with smaller datasets but freezes when processing larger ...
0
votes
2
answers
88
views
Python : filter set/list of tuple based on cardinality property [closed]
I'm looking for a way to filter a set (or list) of tuples based on the number of times an
item appears in one of the other of the position of the tuple.
My current goal is a bit complex so I divided ...
-1
votes
3
answers
219
views
How to generate permutations with constraints
I want to generate all possible lists of ["x","y","z",1,2,3] that are ordered in ascending order. "x", "y" and "z" can be any real numbers ...
1
vote
0
answers
61
views
Generate stable combinations of an unsorted list in python
I have a list made of strings which are not in sorted order. I wish to generate combinations but in such a way that the order of the elements is as in the list. However, Python documentation and its ...
0
votes
3
answers
239
views
Python's itertools permutation different behavior in list comprehension when storing it in a variable
Given a list l=[1,2] I am trying to create a product of permutations. In other words, I am trying to create the following.
from itertools import permutations
l=[1,2]
print([(e1, e2) for e1 in ...
0
votes
1
answer
112
views
More efficient iteration method
I m looking for a better way of doing the following. The code below works but its very slow because I m working with a large dataset. I was trying to also use itertools but somehow I couldnt make it ...
1
vote
1
answer
72
views
Optimizing DataFrame Processing for User Login Intervals with Pandas
I'm working on a function that processes the login times of users on a website. These times are stored in a Pandas DataFrame where the first column indicates a time interval, and the rest indicate if ...
0
votes
2
answers
116
views
After finding all combinations of 5 unique elements, I then want to find which combination appears the most times in a list of lists?
In python I used itertools combination to get all unique 5 combinations:
from itertools import combinations
lst = ["a", "b", "c", "d","e", "f&...
2
votes
2
answers
133
views
How to check if some number can be retrieved as the result of the summation or difference of the given numbers
I have an arbitrary list of positive integers and some number X. I want to check if it is possible to retrieve X using basic operations such as summation and difference.
Any number from the list can ...
1
vote
1
answer
121
views
How do I use something like next() in Python, but it allows me to "step" over iterations like in a for loop? [duplicate]
I have python code that lets me iterate through a list of combinations and I want to skip over the iterations and generate for example every 100th iteration. I have a next() function that makes the ...
-1
votes
1
answer
67
views
Can someone explain this interaction between `zip` and `tee` from itertools? [duplicate]
From my understanding, tee is supposed to make independent copies of an iterator, each of which can be exhausted individually. However, when exhausting the teed copies, sometimes the original iterator ...
-2
votes
1
answer
91
views
I need a universal function for code in python, similar to permutation/combination, have code example
Here's the code example:
res = []
for i in game.keys():
for j in game.keys():
if f'{i}{j}' not in res and f'{j}{i}' not in res:
res.append(f'{i}{j}')
print(res)
I need this, ...
0
votes
0
answers
101
views
How can I resize the gif to fit into the Tkinter window?
This is my code:
import tkinter as tk
from PIL import Image, ImageTk
from itertools import count, cycle
class ImageLabel(tk.Label):
def load(self, im):
if isinstance(im, str):
...
1
vote
0
answers
74
views
Group arrays with same size efficiently
I am trying to group arrays with the same size.
The arrays can be grouped if all of the values (30) within the array are the same, so all values must be the same.
For example: -1.345509 == -1.345509 ...
1
vote
1
answer
37
views
How can i compare each list in a list of lists and compare one of the last elements of the preceding list with first element of next list?
lists = [['1. what is your name','alice','what is your age','98'],
['2. how old are you','24','city of birth','washington 3. None what is your fav subject?'],
['3. what is your fav subject? please ...
0
votes
0
answers
32
views
Behavior of itertools.count, zip and for loops
I have noticed this behavior:
import itertools as iter
truc = iter.count(0)
trac = ["a",'b','c','d','e']
for i in range(3):
zap = [x for x,y in zip(truc,trac)]
print(zap)
which ...
1
vote
2
answers
84
views
Python Sum of array in two different variable
I have this python program
from itertools import product
import itertools
from array import array
for arr in itertools.product(("A", "B", "C"), repeat = 2):
print(arr)...
0
votes
1
answer
56
views
Combinations from itertools behaving weird
I need to identify pairs of subsets of the same size such that they are disjoint and that if we order the sets A={a_1<a_2<...<a_m} and B{b_1<b_2<...<b_m} then for every i=1,...,m a_i&...
1
vote
6
answers
176
views
nth substring multiplicity using itertools
I am trying to write a function that returns a string with the nth substring replaced by a new substring.
I tried the following:
import re
from itertools import count
text = "...
0
votes
1
answer
92
views
Generate list of list round-robin without repetition of items with itertools
If the goal is to achieve f"{x1}-{x2}" pairs where x1 != x2 from a combination, I can do:
import itertools
>>> X = ['1','2','3','4']
>>> [f"-".join(xx) for xx in ...
0
votes
2
answers
122
views
Comparing Columns , Arrays, List using SQL, Numpy or Python List. Would Intertools be valid alternative and faster?
I have two table in SQL
tModel which has 9 columns (ID, Date N1, N2, N3, N4, N5, N6, Flag) and 300 million rows
tPairAP which has 3 columns (ID, N1, N2) and 750 rows
The task I need to to perform is ...
0
votes
2
answers
42
views
Itertools Combinations or product implementation
Here below is the code snippet. I am trying to return a list of all possible matches which combinations does right however I am looking for a way to return all possible matches as for a double round-...
1
vote
1
answer
56
views
Find if a set of lists of 2 values are the result of the possible combination of a n-value list
I have used itertools to find all possible 2-element combination (without repetition) from a set of 10 elements to which I have applied some filtering to reduce the 2-element combination based on ...
-1
votes
1
answer
58
views
Any method to run the number of iteration using itertools .product in python
need to calculate sum of large series in the form s= a1*tf1+a2*tf2+......+an*tfn where n=50 for my problem and each and each value of a1,a2,...,an= range(25,100,25) and tf = random.randint(low=-10, ...
0
votes
1
answer
81
views
How to solve for Memory issue in python while creating a large dataframe
Context:
I have a list of ~80k words which have potential spelling mistakes
(e.g., "apple" vs "applee" vs " apple" vs " aplee ").
I'm planning to great ...
0
votes
2
answers
124
views
Issue with itertools.product that not list as expected
Python itertools.product module not working as expect when I'm extracting string "[1,2], [3,4], [5,6,7], [8,9]" from a json object here:
},
"combos_matrix": "[1,2], [3,4], [5,...
1
vote
1
answer
58
views
Combination of values using dictionary or list [closed]
I'm trying to write a function that takes the values in a list or dictionary and returns the combination of an approximate value. I adjusted the code found here:
from itertools import takewhile, ...
3
votes
2
answers
157
views
Minimum cases of n choose k with respect of n choose q
I have a list
people = ['P1', 'P2', 'P3', 'P4', 'P5', 'P6', 'P7']
allComb4 = list(itertools.combinations(people,4)) # n choose k
#[('P1', 'P2', 'P3', 'P4'), ('P1', 'P2', 'P3', 'P5'), ('P1', 'P2', 'P3'...
0
votes
1
answer
30
views
Indexing itertools permutations without unpacking the intertool object
I have the following
from itertools import islice, permutations
# Function to get a chunk of the itertools object
def get_chunk(iterator, chunk_size):
return list(islice(iterator, chunk_size))
# ...
0
votes
3
answers
222
views
Python method chaining in functional programming style
Below is Python code, where the process_request_non_fp method shows how to handle the problem with IF-ELSE condition (make-api -> load-db -> notify).
I'm trying to get rid of IF-ELSE and chain ...
0
votes
4
answers
82
views
Itertools Combinations will not output sequence larger than 3
In the below code I can not get the result if the output sequence is larger than 3 values.
The below code returns nothing, is there any way to get the below code to return the correct answer of 7175....
2
votes
3
answers
139
views
Python itertools.product challenge to expand a dict with tuples
Given a dictionary like this with some items being tuples...
params = {
'a': 'static',
'b': (1, 2),
'c': ('X', 'Y')
}
I need the "product" of the items into a list of dict like this, ...
1
vote
1
answer
72
views
Optimization of itertools for billion combinations
I deal with the generation of billion combinations using the itertools module in python. For example, I have
A=[[0.0, 963.07438, 1926.14876], [0.0, 3203.76339, 6407.52678], [0.0, 3231.67715, 6463....