---
title: "Python 腦筋急轉彎"
url: https://geminixiang.com/posts/python-brain-teaser/
description: "讓 x+1 is 1+x 為 False、x+2 is 2+x 為 True 的 Python 謎題：從小整數快取（-5 到 256）與自訂 __add__ 兩種解法，看懂 is 與 == 的差別。"
published: 2022-08-15
category: "Programming"
tags: ["python", "trick"]
---

# Python 腦筋急轉彎

# 題目: 讓以下 function 回傳 True

> 原文: https://www.reddit.com/r/Python/comments/cje5yh/short_python_challenge_make_this_return_true/

```python
def check(x):
    if x+1 is 1+x:
        return False
    if x+2 is not 2+x:
        return False
    return True
```

---

## 解答一: -7

在 Python 中，整数 -5 到 256 會預先分配到記憶體，

此時 -7 + 1 得到的 -6，恰好在這範圍之外，

才會出現 -6 is not -6 的情況

## 解答二: 自定義 class

透過實現 **add**，讓他可以與 integer 互動，
但其實就是拿來判斷 integer 後，回傳適當的 boolean (有點作弊 XDD)

```python
class Test(int):
    def __add__(self, v):
        if v == 1:
            return 0
        else:
            return v

---

## About the author

**Ying Xiang Zhao** (geminixiang) — DevOps Engineer, Taipei, Taiwan.

Ying Xiang Zhao（geminixiang）是住在台北的 DevOps 工程師，工作橫跨雲原生基礎設施、CI/CD、ML 模型部署與全端開發。這個部落格記錄 infra、資安與 AI coding agent 的實戰筆記；作品包含開源專案 mikan（把 AI coding agent 帶進 Slack / Telegram / Discord）與 tiny-agent（用四種語言實作的極簡 coding agent），瀏覽器內的影片編輯器 Studio，並經營旅遊分帳工具 SentriPay。

**Open to work** — DevOps Engineer / Platform Engineer / Site Reliability Engineer / AI Infrastructure Engineer · Taipei, Taiwan / Remote. Résumé: https://geminixiang.com/about/ (JSON: https://geminixiang.com/resume.json)

Topics: DevOps, Cloud Native, Kubernetes, Docker, Terraform, Google Cloud, CI/CD, Security, AI coding agents, ML model deployment, TypeScript, Python

Projects:
- [mikan](https://github.com/geminixiang/mikan) — Self-hosted AI coding agent for Slack, Telegram, Discord and GitHub with per-conversation sandboxes
- [tiny-agent](https://github.com/geminixiang/tiny-agent) — Minimal AI coding agents in TypeScript, Go, Python and Rust, plus a book on how they work
- [SentriPay](https://sentripay.com) — Travel expense splitter with multi-currency conversion and shareable, live-synced trip ledgers
- [Studio](https://studio.geminixiang.com) — Browser-based video editor built on WebCodecs

[About](https://geminixiang.com/about/) · [Résumé](https://geminixiang.com/about/) · [LinkedIn](https://linkedin.com/in/geminixiang/) · [GitHub](https://github.com/geminixiang) · [Twitter](https://x.com/geminixiang)
