CodeWars---Python第三题
2016-07-20 17:00
573 查看
1. 问题描述
2. 代码
3. 总结
[b]一、问题描述:[/b]Given two integers, which can be positive and negative, find the sum of all the numbers between including them too and return it. If both numbers are equal return a or b.
[b]二、代码:[/b]
1. my solution
def get_sum(a,b): if a==b: return a else: get_big = max([a,b]) get_small = min([a,b]) nums = xrange(get_small,get_big+1) return sum(nums)
2. other solutions
def get_sum1(a,b): return sum(xrange(min(a,b), max(a,b)+1))
def get_sum2(a, b): return (a + b) * (abs(a - b) + 1) // 2
[b]三、总结[/b]
在python2中,
range()和
xrange()用法相同,但
range()返回一个list,
xrange()返回一个xrange Object,是iterable的;
xrange()占用占用更少的内存空间,因为循环时
xrange()只生成当前的元素,不像
range()一开始就生成list;
在python3中,
range()被移除了,
xrange()被重新命名为
range();
PS: CodeWars刚开始的题目都不是很难得
相关文章推荐
- Python2.7.x 错误和异常
- Python+Selenuim测试网站,只能打开Firefox浏览器却不能打开网页的解决方法
- Python 之 threading
- python组合数据类型
- python联网安装缺乏的包
- Python第一课
- python list 对时间排序小结。
- python对象引用(变量)
- python 映射类型(字典)内建方法
- 关于python的装饰器
- python定制类(以Fib类为例)
- Python-Python 3.x下自定义异常抛出和接收多个值的技巧
- Python爬虫
- Python maplotlib 可视化
- 以写代学:python 模块简介&输出用户指定位数密码的脚本
- 详细介绍windows下使用python pylot进行网站压力测试
- python装饰器初探
- python ConfigParser
- Python黑帽编程1.2 基于VS Code构建Python开发环境
- SyntaxError: Non-ASCII character '\xe4' in file