Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Partition of a set in python

I have b buckets 0....b-1 and m apples 0....m-1. In the beginning all apples are placed in bucket 0.

Then running some analysis causes the apples to be moved among the buckets. I have already implemented this by having a 2D list (as buckets) in which apple ids are removed and appended whenever they need to be moved between buckets. This is, however, very inefficient for my analysis as these movements are in the order of millions or billions. So, I was wondering if there is any better solution out there to implement such a structure?

By the way, the title was chosen as this is very similar to the partitions of a set problem in which no member can be placed in more than 1 subset. Here is also an example with 4 apples and 3 buckets to make it more clear:

time 0:
a=[[0,1,2,3],[],[]]
time 1: (say apple 3 needs to be moved to bucket 2)
a=[[0,1,2],[],[3]]
like image 912
user2517676 Avatar asked Feb 27 '26 23:02

user2517676


1 Answers

The problem with removing an element from a list is that it takes O(n): it takes the order of the number of elements in the list to remove that item.

You better use sets or even better a bitarray that will work in O(1).

For example:

m = 50 #the number of apples
b = 10 #the number of buckets
fls = [False]*m
a = [bitarray(fls) for _ in range(b)]
a[0] = bitarray([True]*m) #add a filled bucket at index 0

def move_apple(apple_id,from_bucket,to_bucket):
    a[from_bucket][apple_id] = False
    a[to_bucket][apple_id] = True
like image 108
Willem Van Onsem Avatar answered Mar 02 '26 12:03

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!