itertools

get all the partitions of the set python with itertools

纵饮孤独 提交于 2020-12-10 03:30:05
问题 How to get all partitions of a set? For example, I have array [1, 2, 3] . I need to get [[1], [2], [3]], [[1], [2, 3]], [[2], [1,3]], [[3], [1, 2]], [[1, 2, 3]] . Now, I wrote this code: def neclusters(S, K): for splits in itertools.combinations(range(len(S)), K): yield np.split(S, 1 + np.array(splits)) But that code don't return [[2],[1,3]] . I could take all permutations of the original set and run this code on them. But can this be made easier? 回答1: I wrote this one for fun: def partition

numba-safe version of itertools.combinations?

谁说胖子不能爱 提交于 2020-08-03 03:18:06
问题 I have some code which loops through a large set of itertools.combinations , which is now a performance bottleneck. I'm trying to turn to numba 's @jit(nopython=True) to speed it up, but I'm running into some issues. First, it seems numba can't handle itertools.combinations itself, per this small example: import itertools import numpy as np from numba import jit arr = [1, 2, 3] c = 2 @jit(nopython=True) def using_it(arr, c): return itertools.combinations(arr, c) for i in using_it(arr, c):

Combinations with repetition in python, where order MATTERS

我与影子孤独终老i 提交于 2020-07-19 06:54:04
问题 From python's Documentation: https://docs.python.org/2/library/itertools.html#itertools.combinations see combinations_with_replacement: "# combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC" I'd like to use the same function, with the bonus of generating "BA", "CA", and "CB". 回答1: itertools.product is definitely the method you're looking for here. As the documentation states, it is effectively a compact for loop; product(A,B) is equivalent to ((x, y) for x in A for y in B) product