菜鸟IT的博客 >> Python
题目:编写一个函数,输入n为偶数时,调用函数求1/2+1/4+...+1/n,(方法2,使用for循环,然后逐个写入数字列表,然后给数字列表求和)
# -*- coding: utf-8 -*-
# 题目:编写一个函数,输入n为偶数时,调用函数求1/2+1/4+...+1/n,
# 当输入n为奇数时,调用函数1/1+1/3+...+1/n
from functools import reduce
n=int(input("请输入n:"))
OuMuShuList=[]
JiMuShuList=[]
if(n%2==0):
for i in range(2,n+1):
if(i%2==0):
OuMuShuList.append(1/i)
print("全部偶分母的分数:",OuMuShuList)
print("全部偶分母分数之和:",reduce(lambda x,y:x+y,OuMuShuList))
elif(n%2!=0):
for i in range(1,n+1):
if(i%2!=0):
JiMuShuList.append(1/i)
print("全部奇分母的分数:",JiMuShuList)
print("全部奇分母分数之和:",reduce(lambda x,y:x+y,JiMuShuList))
菜鸟IT博客[2022.01.25-00:41] 访问:321