Функция hash() в Python позволяет вычислять хеш-значения для различных объектов. Обычно для целых чисел хеш совпадает с их значением, но есть исключения, которые могут удивить даже опытных программистов.
Разбираем, почему hash(-1) и hash(-2) в CPython возвращают одинаковое значение. Рассмотрим особенности работы hash(), внутреннюю реализацию хэширования целых чисел и причину специальной обработки -1.
Вопрос:
Что выведет функция hash() для следующих значений: 1, 0, -1, -2?
India has the largest number of female STEM (Science, Technology, Engineering, Mathematics) graduates in the world. Yet, the female labor force participation rate hovers dismally low (around 30%). This is the great paradox of the Indian woman.
The day begins before sunrise. In Hindu households, the woman draws the Rangoli (colored powder art) at the doorstep, lights the lamp, and offers prayers ( Puja ) for the family’s prosperity. This spiritual start is non-negotiable for many. She then packs lunchboxes—distinctly different for the husband (spicy curry), the child (sandwich), and herself (leftovers). tamil aunty pundai photo gallery
With expanding public roles comes the challenge of managing the "double burden"—balancing demanding careers with traditional domestic expectations. India has the largest number of female STEM
: The "Modern Indian Woman" is increasingly educated and independent, making significant strides in fields once dominated by men, including technology and politics. Education as Empowerment The day begins before sunrise
hash() может показаться незначительной, важно помнить о ней при работе с хэш-функциями и структурами данных, основанных на хэшировании. В большинстве случаев вы не столкнетесь с проблемами, но знание этой детали поможет вам избежать потенциальных ошибок и лучше понимать внутреннее устройство Python.Ключевые выводы:
Для небольших целых чисел в Python используется оптимизация (интернирование).
hash(x) == x для большинства целых чисел, но hash(-1) == -2 из-за внутренней реализации и для предотвращения коллизий.
Это поведение является специфичным для CPython и может отличаться в других реализациях Python (например, PyPy).
Используйте == для сравнения значений и is для сравнения идентичности объектов.
Надеюсь, теперь эта загадка с hash(-1) стала немного понятнее!
hash(-1) всегда возвращает -2, поэтому hash(-1) == hash(-2).__hash__() в пользовательских классах.