代码实现1-100奇数求和,至少3种方式
# 代码实现1-100奇数求和,至少3种方式
# 方法1 循环
# res = 0
# # 1
# for i in range(1, 100):
# if i % 2 == 1:
# res += i
# print(res)
# # 2
# res = 0
# for i in range(1, 100, 2):
# res += i
# print(res)
# 方法2 sum函数,列表解析式,数组切片
# # res = sum([i for i in range(1, 100) if i % 2 == 1])
# # res = sum([i for i in range(1, 100, 2)])
# res = sum(list(range(1, 100))[::2])
# print(res)
# 方法3 函数法
# def func(x, y):
# return x + y
#
#
# res = 0
# for i in range(1, 100, 2):
# res = func(res, i)
# print(res)
# 方法4 lambda函数+reduce
# from functools import reduce
# res = reduce(lambda x, y: x+y, range(1, 100, 2))
# print(res)