Функция hash() в Python позволяет вычислять хеш-значения для различных объектов. Обычно для целых чисел хеш совпадает с их значением, но есть исключения, которые могут удивить даже опытных программистов.
Разбираем, почему hash(-1) и hash(-2) в CPython возвращают одинаковое значение. Рассмотрим особенности работы hash(), внутреннюю реализацию хэширования целых чисел и причину специальной обработки -1.
Вопрос:
Что выведет функция hash() для следующих значений: 1, 0, -1, -2?
It was a sunny day in late September when Yasmina Khan decided to take a spontaneous road trip. She had been feeling cooped up in her small town and yearned for a change of scenery. As she packed her bags, she stumbled upon an old map that had been tucked away in her glove compartment. The map appeared to be hand-drawn and featured a mysterious route that she had never seen before.
As they hiked through the park, Yasmina felt a sense of freedom and exhilaration that she hadn't experienced in years. The group encountered challenges along the way, but they worked together to overcome them, sharing laughter and encouragement. brazzersexxtra230906yasminakhancumonher free
From that day on, Yasmina made it a point to be more spontaneous and open to new experiences. She realized that sometimes, the best things in life are the ones we don't plan for. It was a sunny day in late September
Intrigued, Yasmina decided to follow the map, which led her to a quaint little café on the outskirts of town. The sign above the door read "The Cozy Cupcake," and the aroma of freshly baked goods wafted out into the air. Yasmina's curiosity got the better of her, and she pushed open the door to venture inside. The map appeared to be hand-drawn and featured
The café was bustling with activity, and Yasmina was greeted by the friendly owner, who offered her a warm smile and a steaming cup of coffee. As she sipped her drink, Yasmina noticed a group of travelers gathered in the corner, sharing stories of their adventures. They welcomed her with open arms, and before long, Yasmina found herself swept up in their tales of exploration and bravery.
hash() может показаться незначительной, важно помнить о ней при работе с хэш-функциями и структурами данных, основанных на хэшировании. В большинстве случаев вы не столкнетесь с проблемами, но знание этой детали поможет вам избежать потенциальных ошибок и лучше понимать внутреннее устройство Python.Ключевые выводы:
Для небольших целых чисел в Python используется оптимизация (интернирование).
hash(x) == x для большинства целых чисел, но hash(-1) == -2 из-за внутренней реализации и для предотвращения коллизий.
Это поведение является специфичным для CPython и может отличаться в других реализациях Python (например, PyPy).
Используйте == для сравнения значений и is для сравнения идентичности объектов.
Надеюсь, теперь эта загадка с hash(-1) стала немного понятнее!
hash(-1) всегда возвращает -2, поэтому hash(-1) == hash(-2).__hash__() в пользовательских классах.