37,720
社区成员
发帖
与我相关
我的任务
分享
def isprise(n):
a = [1,2]
b = []
c = []
d = []
s = 0
while True:
b = a[-2:]
for i in b:
s += i
a.append(s)
s = 0
for ii in a[-1:]:
iii = ii
if iii > n - 1:
break
del a[-1:]
for key in a:
if key % 2 == 0:
d.append(key)
return sum(d)
print(isprise(int(input())))
#建立数列
def fib_loop_while(max):
a, b = 0, 1
while max > b:
a, b = b, a + b
# max -= 1
yield a
#计算偶数值项
def isprise(n):
return sum([i if i % 2 ==0 else 0 for i in fib_loop_while(n)])
print(isprise(int(input())))
简单点可以这么写
def isprise(n):
a,b,s = 1,2,0
while b <= n:
if b % 2 == 0:
s += b
a,b = b, a+b
return s
print(isprise(int(input())))
from functools import reduce
def fibonacci_limit(n):
rs = []
a, b = 0, 1
while b < n:
rs.append(b)
a, b = b, a + b
return rs
def fibonacci(n):
source = fibonacci_limit(n)
data_even = filter(lambda x: not x % 2, source)
return reduce(lambda x, y: x+y, list(data_even))
source = input('请输入一个上限:')
print(fibonacci(int(source)))
给一些建议:
1. 实现一个功能,不能就想着一个函数去完成所有功能,而应该做简单的功能分拆,例如,一个函数(fibonacci_limit)去生成数据源,一个函数(fibonacci)去完成运算,这样代码有复用性,逻辑也清晰一点
2. python内置很多工具函数(map, filter, reduce)利用起来, 没必要自己再写算法,虽然也简单,但是累不累
3. 学习一下lambda,保持代码简洁
4. 变量命名要有意义,不要a,b,c,d,ii,iii这样子,别人看不懂,自己以后也看不懂
5. 如果代码简洁,代码注释可以不用怎么写,如果代码长逻辑复杂,关键点还是需要加注释的
6. 给IDE安装PEP8检测器,尽量按规范去写代码
#建立数列
def fib_loop_while(max):
a, b = 0, 1
while max > a:
a, b = b, a + b
max -= 1
yield a
#计算偶数值项
def isprise(n):
return sum([i if i % 2 ==0 else 0 for i in fib_loop_while(n)])
print(isprise(int(input())))