总结遇到的Python的坑
来源:互联网 发布:c语言define的用法 编辑:程序博客网 时间:2024/06/07 02:47
- 左移运算
这篇博客里会列举和总结我自己在使用Python过程中所遇到的坑
左移运算
在Lintcode刷题的时候,遇到了一个位运算的问题,具体问题如下;
A+B问题
给出两个整数a和b, 求他们的和, 但不能使用 + 等数学运算符。说明
a和b都是 32位 整数么?
是的
我可以使用位运算符么?
当然可以
这道题中需要使用位运算来代替加法运算
class Solution: """ @param: a: An integer @param: b: An integer @return: The sum of a and b """ def aplusb(self, a, b): # write your code here if a == 0: return b if b == 0: return a # 不进位相加,通过异或得到原来的位相加后的值 x1 = a^b # 相与后向左移位得到进位 x2 = (a&b)<<1 return self.aplusb(x1, x2)
再提交评测的时候,对于(100,-100)
一直出错,检验算法无误后,改写成cpp代码
class Solution { public: /* * @param a: The first integer * @param b: The second integer * @return: The sum of a and b */ int aplusb(int a, int b) { // write your code here, try to do it without arithmetic operators. if(a==0)return b; if(b==0)return a; int x1 = a^b; int x2 = (a&b)<<1; return aplusb(x1,x2); } };
发现直接就评测通过了,为了找到其中的问题,将迭代过程中每次运行的打印出来
在输入为(100,-1)
而对于python代码的运行结果
-101 200-173 272-445 544-925 1024-1949 2048-3997 4096-8093 8192-16285 16384-32669 32768-65437 65536-130973 131072-262045 262144-524189 524288-1048477 1048576-2097053 2097152-4194205 4194304-8388509 8388608-16777117 16777216-33554333 33554432-67108765 67108864-134217629 134217728-268435357 268435456-536870813 536870912-1073741725 1073741824-2147483549 2147483648......-36028797018963869 36028797018963968-72057594037927837 72057594037927936-144115188075855773 144115188075855872-288230376151711645 288230376151711744-576460752303423389 576460752303423488-1152921504606846877 1152921504606846976-2305843009213693853 2305843009213693952-4611686018427387805 4611686018427387904......
一直循环到报错
在C/C++中,int
型均有32问的长度限制,但是在python中,由于具有大数计算的特性,当超过这个范围时,它会自动进行扩展,所以左移不会停止,造成上述的问题。
阅读全文
0 0
- 总结遇到的Python的坑
- selenium python遇到的问题总结
- boost::python 遇到的一些问题总结
- python中遇到的问题总结
- python中遇到的问题总结
- Python 数值计算 遇到的错误总结
- iOS11遇到的坑总结
- 总结python+Django+mysql项目遇到的一些问题
- 学习Python过程中遇到的错误总结
- 关于Linux安装python画图遇到的一些问题总结
- Python+Selenium学习遇到的问题总结(一)
- python遇到的问题
- python 遇到的异常
- python遇到的问题
- Python 遇到的问题
- python遇到的问题
- 遇到的问题总结
- 遇到的问题总结
- Python Mock的入门
- 算法:区间树
- ARM—HEX转换工具——keystone-engine
- 头文件模板
- 【Centos】7.5版本安装传输工具rz和sz
- 总结遇到的Python的坑
- 【演讲实录】分布式数据库海量数据存储和实时查询实现与应用
- 温故知新(8)委托(二)事件 event
- TCP 和IP的区别
- eclipse中Data Source Explorer的使用方法
- tiny-yolo训练测试(coco训练集混合自己的voc训练集)--20170829
- mybatis传入参数为0被误认为是空字符串的解决方法
- springMVC和其注解方式
- 如何消除重复代码