Marina Abramovic Rhythm 0 Site

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

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

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

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

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

Вопрос:


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

Marina Abramovic Rhythm 0 Site

Abramović’s premise was deceptively simple: she stood motionless and silent for six hours, declaring herself an "object". She placed 72 carefully chosen objects on a table and invited the audience to use them on her in any way they desired, stating, "I take full responsibility". The objects were divided into three categories: : Items such as a rose, a feather, honey, grapes, and wine. Pain/Utility

, exploring its psychological, social, and gender-based implications. Key Scholarly Papers & Articles marina abramovic rhythm 0

The piece stands as a profound commentary on the relationship between the artist and the audience, the dynamics of power, and the fragile veneer of civilization. It forces the viewer to confront an uncomfortable truth: under the right circumstances, the potential for brutality lies within everyone. | Fidelity | Tech Stack | Key Features

| Fidelity | Tech Stack | Key Features | | :--- | :--- | :--- | | (Web) | HTML/CSS, JavaScript, Canvas API | Buttons, avatar as SVG, simple meter | | Medium (Interactive Art) | React + Three.js | 3D abstract figure, particle effects for damage, real-time action logs | | High (Museum Install) | Touchscreen + camera + anonymizing mask | User's silhouette replaces avatar; actions are done via gesture (e.g., raising hand = "threaten") | Canvas API | Buttons

Rhythm 0 is not merely a historical performance; it is a diagnostic tool for understanding the fragility of ethical restraint when structural authority is removed. This paper dissects the performance chronologically, examines its psychological aftermath, and situates it within broader conversations about power, gender, and the art institution as a container for transgression.

“There are 72 objects on the table that one can use on me as desired. I am the object. During this period I take full responsibility. Duration: 6 hours.”

Today, Rhythm 0 stands as a haunting reminder that the most dangerous thing in a room isn't a loaded gun—it’s a group of people who believe their actions don't matter.

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

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

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

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

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

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

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

Вопросы

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

Поделиться

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

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

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

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