How well do you know Python?
Steven D'Aprano
steve at pearwood.info
Tue Jul 5 06:46:30 EDT 2016
On Tue, 5 Jul 2016 07:51 pm, Jussi Piitulainen wrote:
> Chris Angelico writes:
>
>> On Tue, Jul 5, 2016 at 6:36 PM, Peter Otten wrote:
>>> It looks like
>>>
>>> $ python3 -c 'print({1, 2})'
>>> {1, 2}
>>> $ python3 -c 'print({2, 1})'
>>> {1, 2}
>>>
>>> will always print the same output. Can you construct a set from two
>>> small integers where this is not the case? What's the difference?
>>
>> Given that the display (iteration) order of sets is arbitrary, I'm not
>> sure what the significance would ever be, but my guess is that the
>> display order would be the same for any given set, if constructed this
>> way. But it sounds as if you know of a set that behaves differently.
>
> The first thing that came to mind, {-1,-2} and {-2,-1}.
>
> But I haven't a clue. It doesn't happen with -1 and -3, or with another
> pair that I tried, and it doesn't seem to be about object identity.
The hash of most small ints is equal to the int itself:
py> for i in range(100):
... assert hash(i) == i
...
py>
With one exception:
py> hash(-2)
-2
py> hash(-1)
-2
That's because in the C implementation of hash, -1 is used to indicate an
error.
>>> What happens if you replace the ints with strings? Why?
>>
>> Then hash randomization kicks in, and you can run the exact same line
>> of code multiple times and get different results. It's a coin toss.
>
> Oh, nice, a new way to generate random bits in shell scripts.
O_o
You're joking, right?
I'll just leave this here...
https://docs.python.org/3.6/library/secrets.html
--
Steven
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.
More information about the Python-list
mailing list