如何使用 Python 运算符进行性能优化 All In One
如何使用 Python 运算符进行性能优化 All In One
为什么 Python 运算符 // 比 运算符 / 性能更好,运行速度更快呀❓
Why Python operator // is faster than operator /
questions
class Solution:
def numberOfSteps(self, num: int) -> int:
steps: int = 0
while num > 0:
steps += 1
# num % 2 == 1
if(num % 2):
# 为什么 Python 运算符 // 比 运算符 / 性能更好,运行速度更快呀❓
num -= 1
else:
num //= 2
return steps
"""
Runtime
Details
36ms
Beats 93.99%of users with Python3
Memory
Details
15.97mb
Beats 99.95%of users with Python3
"""
https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero/submissions/
demos
Why // operator is faster than / operator in Python? ❌
Why floor division operator is faster than float division in Python? ✅
I tried some test cases and found that the //
operator is faster than the /
operator in Python, so what is going on behind the scenes?
- floor division
//
Runtime 27 ms
Beats 99.64%
Memory 16.3 MB Beats 62.99%
class Solution:
def numberOfSteps(self, num: int) -> int:
steps: int = 0
while num > 0:
steps += 1
if(num % 2 == 0):
# ❓
num //= 2
else:
num -= 1
return steps
- regular division
/
Runtime 41 ms
Beats 80.48%
Memory 16.4 MB Beats 24.29%
class Solution:
def numberOfSteps(self, num: int) -> int:
steps: int = 0
while num > 0:
steps += 1
if(num % 2 == 0):
num /= 2
else:
num -= 1
return steps
Python 算术运算符
https://www.runoob.com/python3/python3-basic-operators.html
refs
©xgqfrms 2012-2025
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/17608914.html
未经授权禁止转载,违者必究!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
2022-08-06 js Array.fill All In One
2022-08-06 leetcode 字符串的排列组合算法题解 All In One
2022-08-06 In modern js you don't need void 0 anymore All In One
2021-08-06 如何使用 Google OCR 把图片中的文字提取出来 All In One
2021-08-06 vue prevent event bubble All In One
2021-08-06 Xbox Series X 双重 NAT bug All In One
2020-08-06 Learning web development with MDN