Q6 Multiples of 3 and 5

1.问题描述

2.代码

3.总结


一、问题描述:
Description:

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Finish the solution so that it returns the sum of all the multiples of 3 or 5 below the number passed in.

Note: If the number is a multiple of both 3 and 5, only count it once.

二、代码:

** My solution **(我的方法是真的chun,o)

  def solution(number): 
    numList = [] 

    for i in xrange(number): 
      if i%3==0 or i%5==0: 
        numList.append(i) 

    return sum(numList)

这些题目都很简单,但是总是不能用最简单的写法完成,总是不习惯写 列表推导式
** Other Solutions **

  • Best Practices
def solution(number): 
    return sum(x for x in range(number) if x % 3 == 0 or x % 5 == 0)
  • Clever
  def solution(number): 
    a3 = (number-1)/3 
    a5 = (number-1)/5 
    a15 = (number-1)/15 
    result = (a3*(a3+1)/2)*3 + (a5*(a5+1)/2)*5 - (a15*(a15+1)/2)*15 
    return result
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容