在python中實(shí)現(xiàn)求輸出1-3+5-7+9-......101的和
第一種:
i=0sum=0a=0while i<102: if i>=1 and i%4==1: sum+=i elif i%2!=0 and i!=1: a=a+i i+=1print(sum-a)
第二種:
a=1b=-3sum1=0sum2=0while a<=101and b>=-99: sum1+=a sum2+=b a+=+4 b+=-4print(sum1+sum2+101)
第三種:
print(sum(range(1,102,4))-sum(range(3,102,4)))
自我反?。?/b>
第一種與第二種是我寫(xiě)的 第三種是我朋友寫(xiě)的 當(dāng)你學(xué)習(xí)Python取得一點(diǎn)點(diǎn)成績(jī)的時(shí)候不要驕傲
補(bǔ)充知識(shí):Python語(yǔ)言求1+3!+5!+7!+9!+50!的幾種思路
有一道Python面試題,求和1+3!+5!+7!+9!+50!
方法一: 常規(guī)思路
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
方法三: 函數(shù)編程
>>> 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
以上這篇在python中實(shí)現(xiàn)求輸出1-3+5-7+9-......101的和就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 基于android studio的layout的xml文件的創(chuàng)建方式2. 解決Android studio xml界面無(wú)法預(yù)覽問(wèn)題3. 詳解Android studio 動(dòng)態(tài)fragment的用法4. Android如何加載Base64編碼格式圖片5. 圖文詳解vue中proto文件的函數(shù)調(diào)用6. Spring Boot和Thymeleaf整合結(jié)合JPA實(shí)現(xiàn)分頁(yè)效果(實(shí)例代碼)7. 什么是python的自省8. .Net Core使用Coravel實(shí)現(xiàn)任務(wù)調(diào)度的完整步驟9. Vuex localStorage的具體使用10. Vue封裝一個(gè)TodoList的案例與瀏覽器本地緩存的應(yīng)用實(shí)現(xiàn)

網(wǎng)公網(wǎng)安備