Функция hash() в Python позволяет вычислять хеш-значения для различных объектов. Обычно для целых чисел хеш совпадает с их значением, но есть исключения, которые могут удивить даже опытных программистов.
Разбираем, почему hash(-1) и hash(-2) в CPython возвращают одинаковое значение. Рассмотрим особенности работы hash(), внутреннюю реализацию хэширования целых чисел и причину специальной обработки -1.
Вопрос:
Что выведет функция hash() для следующих значений: 1, 0, -1, -2?
: Media is increasingly used as a tool for "entertainment-education." Popular series can foster reflection on societal inequalities, shift gender norms, and even influence career choices.
Artificial Intelligence (AI) is currently the most significant catalyst for change in the industry. According to research from IJTSD , AI is revolutionizing: facialabusee840destroyedspergxxx1080phevc top
In the modern era, the lines between our physical lives and our digital experiences have blurred into a single, continuous stream. At the heart of this convergence is , a powerhouse industry that does far more than just "distract" us. It shapes our language, dictates our trends, and provides the cultural glue that connects people across continents. : Media is increasingly used as a tool
: Includes feature films, documentaries, and animated works designed for theatrical release or streaming. At the heart of this convergence is ,
When screens fatigue the eyes, audio thrives. Podcasting has revived the long-form interview and serialized documentary. But more importantly, it has created the "Parasocial Relationship"—the illusion of friendship between a listener and a host. Popular media now includes personalities like Joe Rogan or H3H3, whose influence rivals that of traditional news anchors, based purely on the intimacy of the microphone.
We no longer wait a week for a new episode. We consume entire seasons in a weekend.
The next five years will see the collision of AI and IP. Generative AI is already creating scripts, voice clones, and deepfake visuals. Soon, you may be able to generate a personalized episode of Friends where the characters discuss your specific day. "Interactive AI narratives" will allow you to debate with a hologram of a historical figure or a fictional hero.
hash() может показаться незначительной, важно помнить о ней при работе с хэш-функциями и структурами данных, основанных на хэшировании. В большинстве случаев вы не столкнетесь с проблемами, но знание этой детали поможет вам избежать потенциальных ошибок и лучше понимать внутреннее устройство Python.Ключевые выводы:
Для небольших целых чисел в Python используется оптимизация (интернирование).
hash(x) == x для большинства целых чисел, но hash(-1) == -2 из-за внутренней реализации и для предотвращения коллизий.
Это поведение является специфичным для CPython и может отличаться в других реализациях Python (например, PyPy).
Используйте == для сравнения значений и is для сравнения идентичности объектов.
Надеюсь, теперь эта загадка с hash(-1) стала немного понятнее!
hash(-1) всегда возвращает -2, поэтому hash(-1) == hash(-2).__hash__() в пользовательских классах.