Функция hash() в Python позволяет вычислять хеш-значения для различных объектов. Обычно для целых чисел хеш совпадает с их значением, но есть исключения, которые могут удивить даже опытных программистов.
Разбираем, почему hash(-1) и hash(-2) в CPython возвращают одинаковое значение. Рассмотрим особенности работы hash(), внутреннюю реализацию хэширования целых чисел и причину специальной обработки -1.
Вопрос:
Что выведет функция hash() для следующих значений: 1, 0, -1, -2?
Born on September 8, 1994, in Syracuse, Sicily, she is widely recognized for her work as an amateur performer alongside her partner, Stefano. Her career has earned her several industry honors, including Pornhub Awards
On TikTok, Mori's creative and engaging content quickly resonated with users, catapulting her to fame. Her videos, often showcasing her dancing, lip-syncing, and comedic talents, have been viewed millions of times, earning her a spot among the platform's top creators. Her relatable personality, coupled with her authenticity and kindness, has endeared her to fans worldwide, who eagerly await her next post. vk danika mori
Danika Mori's content primarily consists of variety streaming, gaming, and chatting with her audience. Her streams often feature her playing popular video games, such as Minecraft, Among Us, and Apex Legends. Her engaging personality, humor, and interactivity with her chat have contributed to her popularity. Danika Mori's streams also showcase her creative and artistic side, with art streams and collaborations with other VTubers. Born on September 8, 1994, in Syracuse, Sicily,
: VK acts as a massive video repository. Users frequently search this keyword to find archived video clips or vlogs that might not be easily accessible on more mainstream, heavily moderated sites. Her relatable personality, coupled with her authenticity and
, where the creator confirms their official handles to prevent fraud. VK Видео
: There are several fan clubs and groups dedicated to her on the platform, such as the Danika Mori Fan-Club , which aggregates photos, video snippets, and links to her other platforms like Telegram.
hash() может показаться незначительной, важно помнить о ней при работе с хэш-функциями и структурами данных, основанных на хэшировании. В большинстве случаев вы не столкнетесь с проблемами, но знание этой детали поможет вам избежать потенциальных ошибок и лучше понимать внутреннее устройство Python.Ключевые выводы:
Для небольших целых чисел в Python используется оптимизация (интернирование).
hash(x) == x для большинства целых чисел, но hash(-1) == -2 из-за внутренней реализации и для предотвращения коллизий.
Это поведение является специфичным для CPython и может отличаться в других реализациях Python (например, PyPy).
Используйте == для сравнения значений и is для сравнения идентичности объектов.
Надеюсь, теперь эта загадка с hash(-1) стала немного понятнее!
hash(-1) всегда возвращает -2, поэтому hash(-1) == hash(-2).__hash__() в пользовательских классах.