Skip to content

调试助手

🐛 错误诊断

场景:分析和修复错误

你: 我的代码报错了:

TypeError: unsupported operand type(s) for +: 'int' and 'str'


这是我的代码:
```python
age = 25
message = "I am " + age + " years old"
print(message)

傻妞: 错误分析:

问题原因:

  • Python 不允许直接拼接数字和字符串
  • age 是 int 类型,不能和 str 相加

解决方案(3种):

方案 1:转换为字符串

python
age = 25
message = "I am " + str(age) + " years old"

方案 2:使用 f-string(推荐)

python
age = 25
message = f"I am {age} years old"

方案 3:使用 format

python
age = 25
message = "I am {} years old".format(age)

推荐使用 f-string: ✓ 更清晰 ✓ 更快速 ✓ Python 3.6+ 支持


## 性能分析

### 场景:分析代码性能瓶颈

你: 帮我分析这段代码的性能:

python
def find_duplicates(lst):
    duplicates = []
    for i in range(len(lst)):
        for j in range(i+1, len(lst)):
            if lst[i] == lst[j] and lst[i] not in duplicates:
                duplicates.append(lst[i])
    return duplicates

傻妞: 性能分析:

时间复杂度:O(n²)

  • 外层循环:n 次
  • 内层循环:平均 n/2 次
  • not in 检查:最多 n 次
  • 总计:n × n/2 × n = O(n³)

问题: ⚠️ 三重循环,性能很差 ⚠️ 列表查找是 O(n) ⚠️ 大数据量会很慢

优化版本:

python
def find_duplicates(lst):
    from collections import Counter
    counts = Counter(lst)
    return [item for item, count in counts.items() if count > 1]

优化后: ✓ 时间复杂度:O(n) ✓ 使用 Counter(高度优化) ✓ 代码更简洁 ✓ 速度提升 100 倍+

性能对比:

  • 1000 个元素:原版本 1s,优化版 0.01s
  • 10000 个元素:原版本 100s,优化版 0.1s

---

[上一篇:代码审查](./review.md) | [返回目录](./) | 下一篇:[技术学习](./learning.md)