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