How well does Python set randomization?

First of all, I know that I should never try to describe in this matter, and this is purely hypothetical, so please do not yell at me.

Python collections do not support ordering, as they are hash maps without part of the map. So I was wondering how well they randomize things. This is clearly not enough for cryptography and will not work on ints (because the Python hash is an identifier in ints), but how good is it for games, etc.?

It makes sense that it will work decently, because its modding is on a hash, but I'm not quite sure how good this hash is and how well it will work for randomization.

PS: Sets will always return the same shuffle for the same values, but you can assume that this is not a problem.

+4
source share
1 answer

a sethas no order; therefore, by definition, it cannot randomize the order. The iteration order cannot be used if you care about the order. As BrenBam says, if you care about the order in any way, you cannot rely on it because it is an implementation detail.

The right way to randomize order random.shuffle

some_set_of_stuff = set(...)
some_list_of_stuff = list(some_set_of_stuff)  # you MUST make an ordered container for this!
random.shuffle(some_list_of_stuff)

Or you can use random.sampleif you really need to.

some_set_of_stuff = set(...)
randomized = random.sample(some_set_of_stuff, len(some_set_of_stuff))
+2
source

Source: https://habr.com/ru/post/1621840/


All Articles