Q3

1. 问题描述

2. 代码

3. 总结


一、问题描述:

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.

二、代码:
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
三、总结
  • 在python2中,range()xrange() 用法相同,但range() 返回一个list,xrange() 返回一个xrange Object,是iterable的;
  • xrange()占用占用更少的内存空间,因为循环时xrange() 只生成当前的元素,不像 range() 一开始就生成list;
  • 在python3中,range() 被移除了,xrange() 被重新命名为range()

PS: CodeWars刚开始的题目都不是很难的

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,776评论 0 33
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,934评论 0 23
  • http://python.jobbole.com/85231/ 关于专业技能写完项目接着写写一名3年工作经验的J...
    燕京博士阅读 7,629评论 1 118
  • 时间似是被撕开了道口子 回忆在冷冽中暴露 那还淌着血的泪 企图用一张网,将它保留 冬,蓄满了力 将春在背后抓紧 漫...
    怡南阅读 1,890评论 8 10
  • 上周练琴只练了三天,其中只有一天练得好。琴行阿姨可能觉得太浪费他们的时间了,所以建议我买琴了。我也是这么想的,在和...
    圈_圈_阅读 221评论 0 0