Converting from a tuple to a set reverses the order of "8"

Asked 1 years ago, Updated 1 years ago, 325 views

I don't know the cause/resolution, so let me ask you a question.
As shown in the code below, we took out all 10 elements and converted them from tuples to sets.

#Number of elements
J = 10

# All combinations of elements
subsets = [
    s
    for jin range (J+1)
    for in combinations (range(J), j)
]

# Convert each combination from tuple to set.Compare the original tuple on the left and the set on the right.
for jin range (J):
    for s_union_jin subsets:
        s_union_j_set=set(s_union_j)
        print(s_union_j,s_union_j_set) 
        

As a result, the original tuple and set are printed as follows, but for some reason (X, 8 or 9) (X is less than 8), the position of the value in parentheses is reversed (see yellow highlight)
This phenomenon occurs when the value is greater than or equal to 8, and there seems to be no reversal when the value is less than or equal to that value.

Enter a description of the image here

What is the cause of this and how do I convert it into a set while maintaining the original order relationship?

Thank you for your cooperation

python

2022-11-30 00:16

2 Answers

It's a story with a lot of imagination.

Python's set is implemented in the hash table.

For example, converting [1,2,8] to set
For a set of sufficiently few elements, the element in the route array is 8,
So suppose you manage the hash value divided by 8 and then put it together.
The hash of numeric objects is usually the same as the number, so

[
[8], # 0
[1], # 1
[2], # 2
[], # 3
[], # 4
[], # 5
[], # 6
[], # 7
]

It has an internal structure called print, and when you do print, it will probably be displayed from the top to the
You may have a question-like phenomenon.

What's really going on is the CPython code
https://github.com/python/cpython/blob/main/Objects/setobject.c
It seems that you will understand if you read .I gave up.


2022-11-30 01:44

If it is sorted(s_union_j_set), we can restore the order of the original tuples, but if you know why the order is reversed if there are more than 8 numbers, please let us know.


2022-11-30 05:03

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.