Функция hash() в Python позволяет вычислять хеш-значения для различных объектов. Обычно для целых чисел хеш совпадает с их значением, но есть исключения, которые могут удивить даже опытных программистов.
Разбираем, почему hash(-1) и hash(-2) в CPython возвращают одинаковое значение. Рассмотрим особенности работы hash(), внутреннюю реализацию хэширования целых чисел и причину специальной обработки -1.
Вопрос:
Что выведет функция hash() для следующих значений: 1, 0, -1, -2?
Indonesia has one of the world’s largest TikTok user bases. It’s no longer just an entertainment app; it’s a search engine, a marketplace (TikTok Shop), and the primary source of music discovery.
Indonesia is often called a "Mobile First" nation. For the youth, life happens on a smartphone. bocil disuruh muasin memek si kakak toge indo18 new
Indonesian youth culture is characterized by a "hyper-local" pride. While they are connected to the global internet, they are increasingly looking inward—championing their own brands, their own sounds, and their own traditional textiles. It is a generation that is tech-savvy, socially conscious, and deeply creative. Indonesia has one of the world’s largest TikTok user bases
Massive multi-day festivals like We The Fest and Joyland have become annual pilgrimages for fashion and music enthusiasts. 3. Fashion: Thrifting vs. Local Brands For the youth, life happens on a smartphone
Here is a deep dive into the trends shaping the lives of young Indonesians today. 1. The Digital-First Lifestyle
The word (derived from "scene") has become a defining buzzword. It refers to the underground or indie creative communities that prioritize authenticity over mainstream appeal.
hash() может показаться незначительной, важно помнить о ней при работе с хэш-функциями и структурами данных, основанных на хэшировании. В большинстве случаев вы не столкнетесь с проблемами, но знание этой детали поможет вам избежать потенциальных ошибок и лучше понимать внутреннее устройство Python.Ключевые выводы:
Для небольших целых чисел в Python используется оптимизация (интернирование).
hash(x) == x для большинства целых чисел, но hash(-1) == -2 из-за внутренней реализации и для предотвращения коллизий.
Это поведение является специфичным для CPython и может отличаться в других реализациях Python (например, PyPy).
Используйте == для сравнения значений и is для сравнения идентичности объектов.
Надеюсь, теперь эта загадка с hash(-1) стала немного понятнее!
hash(-1) всегда возвращает -2, поэтому hash(-1) == hash(-2).__hash__() в пользовательских классах.