在python中实现求输出1-3+5-7+9-......101的和

作者:第二i 时间:2022-10-08 16:33:14 

第一种:


i=0
sum=0
a=0
while i<102:
if i>=1 and i%4==1:
 sum+=i
elif i%2!=0 and i!=1:
 a=a+i
i+=1
print(sum-a)

第二种:


a=1
b=-3
sum1=0
sum2=0
while a<=101and b>=-99:
sum1+=a
sum2+=b
a+=+4
b+=-4
print(sum1+sum2+101)

第三种:

print(sum(range(1,102,4))-sum(range(3,102,4)))

自我反省:

第一种与第二种是我写的 第三种是我朋友写的 当你学习Python取得一点点成绩的时候不要骄傲

补充知识:Python语言求1+3!+5!+7!+9!+50!的几种思路

有一道Python面试题,求和1+3!+5!+7!+9!+50!

方法一: 常规思路


L = [1, 3, 5, 7, 9, 50]

def func(n):
if n == 1:
 return 1
else:
 return n * func(n-1)

total = 0

for i in L:
total = total + func(i)
print(total)

方法二: 递归求和


>>> def func(n):
...  return 1 if n == 1 else n * func(n-1)
>>> sum([func(i) for i in [1, 3, 5, 7, 9, 50]])
30414093201713378043612608166064768844377641568960512000000368047L

方法三: 函数编程


>>> from functools import reduce
>>> sum([reduce(lambda x,y:x*y, range(1, i+1)) for i in list(range(1, 10, 2)) + [50]])
30414093201713378043612608166064768844377641568960512000000368047L

方法四: 借助模块


>>> from scipy.special import factorial
>>> sum(factorial([1, 3, 5, 7, 9, 50], exact=True))
30414093201713378043612608166064768844377641568960512000000368047L

来源:https://blog.csdn.net/weixin_42785547/article/details/82733442

标签:python,输出和
0
投稿

猜你喜欢

  • Python爬虫 批量爬取下载抖音视频代码实例

    2021-08-02 23:25:10
  • nodejs使用socket5进行代理请求的实现

    2024-05-09 14:49:44
  • asp下几种常用排序算法

    2011-04-18 10:33:00
  • MySQL实现字符串截取的图文教程

    2024-01-16 05:44:05
  • Python Matplotlib绘制动画的代码详解

    2022-08-19 20:21:03
  • Python yield的用法实例分析

    2022-08-03 10:00:21
  • CSS Type set: 在线字体调整工具

    2008-03-02 15:36:00
  • PHP中文字符串截断无乱码解决方法

    2024-05-11 09:44:55
  • YUI学习笔记(1)

    2009-01-12 18:06:00
  • Golang中异常处理机制详解

    2024-02-17 17:05:50
  • SQL Server数据库基本概念、组成、常用对象与约束

    2024-01-14 02:16:01
  • Python实现的Kmeans++算法实例

    2023-01-05 22:28:36
  • python datetime中strptime用法详解

    2022-03-08 19:31:48
  • 一文教你用Python中progress库实现进度条

    2023-09-14 10:28:31
  • pandas实现datetime64与unix时间戳互转

    2022-10-28 18:59:11
  • Golang数据类型比较详解

    2023-07-17 10:11:21
  • python实现银行管理系统

    2021-07-09 00:33:49
  • Mysql中的Btree与Hash索引比较

    2024-01-16 12:56:49
  • Burp Suite Pro安装和配置使用教程详解

    2023-12-18 06:56:43
  • python获取多线程及子线程的返回值

    2022-01-17 20:44:07
  • asp之家 网络编程 m.aspxhome.com