Q3

作者: realjk | 来源:发表于2016-07-21 11:19 被阅读0次

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刚开始的题目都不是很难的

相关文章

网友评论

      本文标题:Q3

      本文链接:https://www.haomeiwen.com/subject/lxjbjttx.html