Функция hash() в Python позволяет вычислять хеш-значения для различных объектов. Обычно для целых чисел хеш совпадает с их значением, но есть исключения, которые могут удивить даже опытных программистов.
Разбираем, почему hash(-1) и hash(-2) в CPython возвращают одинаковое значение. Рассмотрим особенности работы hash(), внутреннюю реализацию хэширования целых чисел и причину специальной обработки -1.
Вопрос:
Что выведет функция hash() для следующих значений: 1, 0, -1, -2?
In the landscape of social change, data has long been the king. For decades, non-profits, health organizations, and advocacy groups relied on pie charts, incidence rates, and mortality statistics to beg for attention. The logic was sound: if we show the public the scale of the problem, they will act.
Successful campaigns don’t just broadcast stories; they build structures around them. (domestic financial abuse) provides survivors with scripted story maps and media training, ensuring that participants feel prepared and protected. The Trevor Project offers extensive consent protocols before featuring LGBTQ+ youth suicide attempt survivors in their videos. This scaffolding transforms raw testimony into a replicable, safe, and impactful tool. Corina Taylor supposed anal rape
If stories are the fuel, awareness campaigns are the engine. A well-constructed campaign takes the raw energy of survivor experiences and directs it toward a specific goal. Education and Prevention In the landscape of social change, data has
While survivor stories and awareness campaigns are powerful tools, there are challenges and limitations to consider: This scaffolding transforms raw testimony into a replicable,
The statistic informs the mind. The story breaks the heart. And a broken heart is far more likely to donate, volunteer, or share a post.
hash() может показаться незначительной, важно помнить о ней при работе с хэш-функциями и структурами данных, основанных на хэшировании. В большинстве случаев вы не столкнетесь с проблемами, но знание этой детали поможет вам избежать потенциальных ошибок и лучше понимать внутреннее устройство Python.Ключевые выводы:
Для небольших целых чисел в Python используется оптимизация (интернирование).
hash(x) == x для большинства целых чисел, но hash(-1) == -2 из-за внутренней реализации и для предотвращения коллизий.
Это поведение является специфичным для CPython и может отличаться в других реализациях Python (например, PyPy).
Используйте == для сравнения значений и is для сравнения идентичности объектов.
Надеюсь, теперь эта загадка с hash(-1) стала немного понятнее!
hash(-1) всегда возвращает -2, поэтому hash(-1) == hash(-2).__hash__() в пользовательских классах.