在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)))
自我反省:
第一種與第二種是我寫(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. 利用promise及參數(shù)解構(gòu)封裝ajax請(qǐng)求的方法2. JSP數(shù)據(jù)交互實(shí)現(xiàn)過(guò)程解析3. windows服務(wù)器使用IIS時(shí)thinkphp搜索中文無(wú)效問(wèn)題4. .NET中l(wèi)ambda表達(dá)式合并問(wèn)題及解決方法5. Nginx+php配置文件及原理解析6. 淺談python出錯(cuò)時(shí)traceback的解讀7. ASP 信息提示函數(shù)并作返回或者轉(zhuǎn)向8. Ajax實(shí)現(xiàn)表格中信息不刷新頁(yè)面進(jìn)行更新數(shù)據(jù)9. Python importlib動(dòng)態(tài)導(dǎo)入模塊實(shí)現(xiàn)代碼10. python matplotlib:plt.scatter() 大小和顏色參數(shù)詳解
