Modoo Marble Codex - Updated

Загадочная функция hash в Python

Функция hash() в Python позволяет вычислять хеш-значения для различных объектов. Обычно для целых чисел хеш совпадает с их значением, но есть исключения, которые могут удивить даже опытных программистов. 

Разбираем, почему hash(-1) и hash(-2) в CPython возвращают одинаковое значение. Рассмотрим особенности работы hash(), внутреннюю реализацию хэширования целых чисел и причину специальной обработки -1.

Вопрос на интервью

Однажды на собеседовании мне задали, казалось бы, простой вопрос.

Вопрос:


Что выведет функция hash() для следующих значений: 1, 0, -1, -2?

Modoo Marble Codex - Updated

Jaehoon almost choked on his ramen. He tapped.

: Use the “Codex Completion Ticket” (new item from Daily Login) to automatically register any missing Common-tier item. modoo marble codex updated

Newer characters in the Codex now feature two "built-in" abilities, freeing up your pendant slots for even more customization. 2. The Codex Tier List (2024–2025 Updates) Jaehoon almost choked on his ramen

These have become essential for late-game survival, offering percentage-based defenses that weren't available in older versions. Newer characters in the Codex now feature two

Critics might argue that the Codex updates made the game too complex for the casual audience. Indeed, the learning curve has steepened. New players must now navigate a web of patch notes and meta reports to understand why their starting deck is ineffective. However, this complexity is a necessary evolution. The board game genre is inherently limited by the simplicity of its rules; without the layers of strategy introduced by the Updated Codex, Modoo Marble would have risked becoming repetitive. By turning the game into a puzzle of resource management—where every toll paid or skill card used is a calculated investment—the update secured the game's place in the competitive mobile market.

The Codex now includes expanded districts previously uncharted in the standard rotations. Players will now traverse the neon-lit boulevards of cyberpunk districts and the historic, cobblestoned streets of ancient capitals. These new zones are not merely aesthetic; they function as distinct economic biomes. Owning a monopoly in the new "Tech Hubs" yields higher risk but exponential rewards, whereas the "Heritage Districts" offer stable, defensive income.

Хотя эта особенность hash() может показаться незначительной, важно помнить о ней при работе с хэш-функциями и структурами данных, основанных на хэшировании. В большинстве случаев вы не столкнетесь с проблемами, но знание этой детали поможет вам избежать потенциальных ошибок и лучше понимать внутреннее устройство Python.

Ключевые выводы:

  • Для небольших целых чисел в Python используется оптимизация (интернирование).
     

  • hash(x) == x для большинства целых чисел, но hash(-1) == -2 из-за внутренней реализации и для предотвращения коллизий.
     

  • Это поведение является специфичным для CPython и может отличаться в других реализациях Python (например, PyPy).
     

  • Используйте == для сравнения значений и is для сравнения идентичности объектов.

Надеюсь, теперь эта загадка с hash(-1) стала немного понятнее!

Вопросы

Почему значения hash(-1) и hash(-2) могут совпадать в Python?
Можно ли изменить поведение функции hash() для чисел?

Поделиться

Обсудить проект с командой LighTech

Забронировать встречу

Примеры реализации проектов

Обсудить проект
Имя
Связаться
Сообщение
Прикрепить файл +
Запрос на получение файлов
Имя
Отправить файлы
Сообщение
Спасибо!
Ваша заявка отправлена
После обработки наш менеджер свяжется с вами