Multiples of 3 and 5
2014-09-10 11:29
260 查看
‘’‘
注:不标题题目出处
If we list all the natural numbers below 10that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiplesis 23.
Find the sum of all the multiples of 3 or 5below 1000.
某个数以内的所有3,5的倍数的和
'''
对于这个问题,大家一般想到的会是如下解决方案:
简单快捷
对于python来说,似乎还有更好的处理方案:
这样处理虽然更符合python,我们是否可以让它一般化
处理成函数:
对于返回值的处理,还可以使用reduce函数:
说明:借鉴这些题目,让自己熟悉语法,熟悉一些算法,让自己的表达更好一点。
这里引用他人的一个想法,这是欧拉项目的题目,所以都可以用数学方法来解决
想法:某个数字范围内,对与3或5的倍数的和,可以理解为3的倍数和
Python表示:
注:不标题题目出处
If we list all the natural numbers below 10that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiplesis 23.
Find the sum of all the multiples of 3 or 5below 1000.
某个数以内的所有3,5的倍数的和
'''
对于这个问题,大家一般想到的会是如下解决方案:
n = 1000 res = 0 for i in xrange(n): <span style="white-space:pre"> </span>if i % 3 == 0 or i % 5 == 0: <span style="white-space:pre"> </span>res += i print res
简单快捷
对于python来说,似乎还有更好的处理方案:
n = 1000 numbers = [i for i in xrange(n) if i % 3 == 0 or i % 5 == 0] print sum(numbers)
这样处理虽然更符合python,我们是否可以让它一般化
处理成函数:
def multiples_sum(n, one=3, two=5): <span style="white-space:pre"> </span>return sum([i for i in range(n) if i % one == 0 or i % two == 0]) print multiples_sum(1000)
对于返回值的处理,还可以使用reduce函数:
def multiples_reduce(n, one=3, two=5): <span style="white-space:pre"> </span>return reduce(lambda x,y : x+y, [i for i in range(n) if i % one == 0 or i % two == 0])
说明:借鉴这些题目,让自己熟悉语法,熟悉一些算法,让自己的表达更好一点。
这里引用他人的一个想法,这是欧拉项目的题目,所以都可以用数学方法来解决
想法:某个数字范围内,对与3或5的倍数的和,可以理解为3的倍数和
Python表示:
def multiples_sum(n, one=3, two=5): three = one * two numbers = [i for i in xrange(n)] return sum(numbers[one:n:one]) + sum(numbers[two:n:two]) - sum(numbers[three:n:three])
相关文章推荐
- 1 Multiples of 3 and 5 - Project Euler
- Project Euler Problem 1 - Multiples of 3 and 5
- (Problem 1)Multiples of 3 and 5
- (Problem 1)Multiples of 3 and 5
- Problem 1:Multiples of 3 and 5
- Project Euler 001 Multiples of 3 and 5
- Project Euler #1: Multiples of 3 and 5
- (Problem 1)Multiples of 3 and 5
- Multiples of 3 and 5
- Multiples of 3 and 5
- 【Project Euler 1】Multiples of 3 and 5
- Project Euler Problem 1: Multiples of 3 and 5
- Multiples of 3 and 5
- System and method for parallel execution of memory transactions using multiple memory models, including SSO, TSO, PSO and RMO
- PE 001 Multiples of 3 and 5
- Project Euler 1 Multiples of 3 and 5
- Identifying multiple/single values of metadata and recording into XML via .NET Client Object Model
- Multiples of 3 and 5
- PE1 Multiples of 3 and 5
- Problem 1 Multiples of 3 and 5