当前位置:网站首页>python100例項
python100例項
2020-11-06 21:13:00 【itread01】
例項001:數字組合 題目 有四個數字:1、2、3、4,能組成多少個互不相同且無重複數字的三位數?各是多少? 程式分析 遍歷全部可能,把有重複的剃掉。 total=0 for i in range(1,5): for j in range(1,5): for k in range(1,5): if ((i!=j)and(j!=k)and(k!=i)): print(i,j,k) total+=1 print(total) 簡便方法 用itertools中的permutations即可。 import itertools sum2=0 a=[1,2,3,4] for i in itertools.permutations(a,3): print(i) sum2+=1 print(sum2) 例項002:“個稅計算” 題目 企業發放的獎金根據利潤提成。利潤(I)低於或等於10萬元時,獎金可提10%;利潤高於10萬元,低於20萬元時,低於10萬元的部分按10%提成,高於10萬元的部分,可提成7.5%;20萬到40萬之間時,高於20萬元的部分,可提成5%;40萬到60萬之間時高於40萬元的部分,可提成3%;60萬到100萬之間時,高於60萬元的部分,可提成1.5%,高於100萬元時,超過100萬元的部分按1%提成,從鍵盤輸入當月利潤I,求應發放獎金總數? 程式分析 分割槽間計算即可。 profit=int(input('Show me the money: ')) bonus=0 thresholds=[100000,100000,200000,200000,400000] rates=[0.1,0.075,0.05,0.03,0.015,0.01] for i in range(len(thresholds)): if profit<=thresholds[i]: bonus+=profit*rates[i] profit=0 break else: bonus+=thresholds[i]*rates[i] profit-=thresholds[i] bonus+=profit*rates[-1] print(bonus) 例項003:完全平方數 題目 一個整數,它加上100後是一個完全平方數,再加上168又是一個完全平方數,請問該數是多少? 程式分析 因為168對於指數爆炸來說實在太小了,所以可以直接省略數學分析,用最樸素的方法來獲取上限: n=0 while (n+1)**2-n*n<=168: n+=1 print(n+1) 思路是:最壞的結果是n的平方與(n+1)的平方剛好差168,由於是平方的關係,不可能存在比這更大的間隙。 至於判斷是否是完全平方數,最簡單的方法是:平方根的值小數為0即可。 結合起來: n=0 while (n+1)**2-n*n<=168: n+=1 for i in range((n+1)**2): if i**0.5==int(i**0.5) and (i+168)**0.5==int((i+168)**0.5): print(i-100) 例項004:這天第幾天 題目 輸入某年某月某日,判斷這一天是這一年的第幾天? 程式分析 特殊情況,閏年時需考慮二月多加一天: def isLeapYear(y): return (y%400==0 or (y%4==0 and y%100!=0)) DofM=[0,31,28,31,30,31,30,31,31,30,31,30] res=0 year=int(input('Year:')) month=int(input('Month:')) day=int(input('day:')) if isLeapYear(year): DofM[2]+=1 for i in range(month): res+=DofM[i] print(res+day) 例項005:三數排序 題目 輸入三個整數x,y,z,請把這三個數由小到大輸出。 程式分析 練練手就隨便找個排序演算法實現一下,偷懶就直接調函式。 raw=[] for i in range(3): x=int(input('int%d: '%(i))) raw.append(x) for i in range(len(raw)): for j in range(i,len(raw)): if raw[i]>raw[j]: raw[i],raw[j]=raw[j],raw[i] print(raw) raw2=[] for i in range(3): x=int(input('int%d: '%(i))) raw2.append(x) print(sorted(raw2)) 例項006:斐波那契數列 題目 斐波那契數列。 程式分析 斐波那契數列(Fibonacci sequence),從1,1開始,後面每一項等於前面兩項之和。圖方便就遞迴實現,圖效能就用迴圈。 遞迴實現 def Fib(n): return 1 if n<=2 else Fib(n-1)+Fib(n-2) print(Fib(int(input()))) 樸素實現 target=int(input()) res=0 a,b=1,1 for i in range(target-1): a,b=b,a+b print(a) 例項007:copy 題目 將一個列表的資料複製到另一個列表中。 程式分析 使用列表[:],拿不準可以呼叫copy模組。 import copy a = [1,2,3,4,['a','b']] b = a # 賦值 c = a[:] # 淺拷貝 d = copy.copy(a) # 淺拷貝 e = copy.deepcopy(a) # 深拷貝 a.append(5) a[4].append('c') print('a=',a) print('b=',b) print('c=',c) print('d=',d) print('e=',e) ============ RESTART: F:\PyWorkspace\Python100\100examples\007.py ============ a= [1, 2, 3, 4, ['a', 'b', 'c'], 5] b= [1, 2, 3, 4, ['a', 'b', 'c'], 5] c= [1, 2, 3, 4, ['a', 'b', 'c']] d= [1, 2, 3, 4, ['a', 'b', 'c']] e= [1, 2, 3, 4, ['a', 'b']] 例項008:九九乘法表 題目 輸出 9*9 乘法口訣表。 程式分析 分行與列考慮,共9行9列,i控制行,j控制列。 for i in range(1,10): for j in range(1,i+1): print('%d*%d=%2ld '%(i,j,i*j),end='') print() 例項009:暫停一秒輸出 題目 暫停一秒輸出。 程式分析 使用 time 模組的 sleep() 函式。 import time for i in range(4): print(str(int(time.time()))[-2:]) time.sleep(1) 例項010:給人看的時間 題目 暫停一秒輸出,並格式化當前時間。 程式分析 同009. import time for i in range(4): print(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))) time.sleep(1) 例項011:養兔子 題目 有一對兔子,從出生後第3個月起每個月都生一對兔子,小兔子長到第三個月後每個月又生一對兔子,假如兔子都不死,問每個月的兔子總數為多少? 程式分析 我認為原文的解法有點扯,沒有考慮3個月成熟的問題,人家還是嬰兒怎麼生孩子?考慮到三個月成熟,可以構建四個資料,其中:一月兔每個月長大成為二月兔,二月兔變三月兔,三月兔變成年兔,成年兔(包括新成熟的三月兔)生等量的一月兔。 month=int(input('繁殖幾個月?: ')) month_1=1 month_2=0 month_3=0 month_elder=0 for i in range(month): month_1,month_2,month_3,month_elder=month_elder+month_3,month_1,month_2,month_elder+month_3 print('第%d個月共'%(i+1),month_1+month_2+month_3+month_elder,'對兔子') print('其中1月兔:',month_1) print('其中2月兔:',month_2) print('其中3月兔:',month_3) print('其中成年兔:',month_elder) 例項012:100到200的素數 題目 判斷101-200之間有多少個素數,並輸出所有素數。 程式分析 判斷素數的方法:用一個數分別去除2到sqrt(這個數),如果能被整除,則表明此數不是素數,反之是素數。 用else可以進一步簡化程式碼. import math for i in range(100,200): flag=0 for j in range(2,round(math.sqrt(i))+1): if i%j==0: flag=1 break if flag: continue print(i) print('\nSimplify the code with "else"\n') for i in range(100,200): for j in range(2,round(math.sqrt(i))+1): if i%j==0: break else: print(i) 例項013:所有水仙花數 題目 打印出所有的"水仙花數",所謂"水仙花數"是指一個三位數,其各位數字立方和等於該數本身。例如:153是一個"水仙花數",因為153=1的三次方+5的三次方+3的三次方。 程式分析 利用for迴圈控制100-999個數,每個數分解出個位,十位,百位。 for i in range(100,1000): s=str(i) one=int(s[-1]) ten=int(s[-2]) hun=int(s[-3]) if i == one**3+ten**3+hun**3: print(i) 例項014:分解質因數 題目 將一個整數分解質因數。例如:輸入90,打印出90=233*5。 程式分析 根本不需要判斷是否是質數,從2開始向數本身遍歷,能整除的肯定是最小的質數。 target=int(input('輸入一個整數:')) print(target,'= ',end='') if target<0: target=abs(target) print('-1*',end='') flag=0 if target<=1: print(target) flag=1 while True: if flag: break for i in range(2,int(target+1)): if target%i==0: print("%d"%i,end='') if target==i: flag=1 break print('*',end='') target/=i break 例項015:分數歸檔 題目 利用條件運算子的巢狀來完成此題:學習成績>=90分的同學用A表示,60-89分之間的用B表示,60分以下的用C表示。 程式分析 用條件判斷即可。 points=int(input('輸入分數:')) if points>=90: grade='A' elif points<60: grade='C' else: grade='B' print(grade) 例項016:輸出日期 題目 輸出指定格式的日期。 程式分析 使用 datetime 模組。 import datetime print(datetime.date.today()) print(datetime.date(2333,2,3)) print(datetime.date.today().strftime('%d/%m/%Y')) day=datetime.date(1111,2,3) day=day.replace(year=day.year+22) print(day) 例項017:字串構成 題目 輸入一行字元,分別統計出其中英文字母、空格、數字和其它字元的個數。 程式分析 利用 while 或 for 語句,條件為輸入的字元不為 ‘\n’。 string=input("輸入字串:") alp=0 num=0 spa=0 oth=0 for i in range(len(string)): if string[i].isspace(): spa+=1 elif string[i].isdigit(): num+=1 elif string[i].isalpha(): alp+=1 else: oth+=1 print('space: ',spa) print('digit: ',num) print('alpha: ',alp) print('other: ',oth) 例項018:復讀機相加 題目 求s=a+aa+aaa+aaaa+aa…a的值,其中a是一個數字。例如2+22+222+2222+22222(此時共有5個數相加),幾個數相加由鍵盤控制。 程式分析 用字串解決。 a=input('被加數字:') n=int(input('加幾次?:')) res=0 for i in range(n): res+=int(a) a+=a[0] print('結果是:',res) 例項019:完數 題目 一個數如果恰好等於它的因子之和,這個數就稱為"完數"。例如6=1+2+3.程式設計找出1000以內的所有完數。 程式分析 將每一對因子加進集合,在這個過程中已經自動去重。最後的結果要求不計算其本身。 def factor(num): target=int(num) res=set() for i in range(1,num): if num%i==0: res.add(i) res.add(num/i) return res for i in range(2,1001): if i==sum(factor(i))-i: print(i) 例項020:高空拋物 題目 一球從100米高度自由落下,每次落地後反跳回原高度的一半;再落下,求它在第10次落地時,共經過多少米?第10次反彈多高? 程式分析 無 high=200. total=100 for i in range(10): high/=2 total+=high print(high/2) print('總長:',total) 例項021:猴子偷桃 題目 猴子吃桃問題:猴子第一天摘下若干個桃子,當即吃了一半,還不癮,又多吃了一個第二天早上又將剩下的桃子吃掉一半,又多吃了一個。以後每天早上都吃了前一天剩下的一半零一個。到第10天早上想再吃時,見只剩下一個桃子了。求第一天共摘了多少。 程式分析 按規則反向推斷:猴子有一個桃子,他偷來一個桃子,覺得不夠又偷來了與手上等量的桃子,一共偷了9天。 peach=1 for i in range(9): peach=(peach+1)*2 print(peach) 例項022:比賽對手 題目 兩個乒乓球隊進行比賽,各出三人。甲隊為a,b,c三人,乙隊為x,y,z三人。已抽籤決定比賽名單。有人向隊員打聽比賽的名單。a說他不和x比,c說他不和x,z比,請程式設計序找出三隊賽手的名單。 程式分析 找到條件下不重複的三個對手即可。 a=set(['x','y','z']) b=set(['x','y','z']) c=set(['x','y','z']) c-=set(('x','y')) a-=set('x') for i in a: for j in b: for k in c: if len(set((i,j,k)))==3: print('a:%s,b:%s,c:%s'%(i,j,k)) 例項023:畫菱形 題目 打印出如下圖案(菱形): * *** ***** ******* ***** *** * 程式分析 遞迴呼叫即可。 def draw(num): a="*"*(2*(4-num)+1) print(a.center(9,' ')) if num!=1: draw(num-1) print(a.center(9,' ')) draw(4) 例項024:斐波那契數列II 題目 有一分數序列:2/1,3/2,5/3,8/5,13/8,21/13…求出這個數列的前20項之和。 程式分析 就是斐波那契數列的後一項除以前一項。 a = 2.0 b = 1.0 s = 0 for n in range(1,21): s += a / b a,b = a + b,a print (s) 例項025: 階乘求和 題目 求1+2!+3!+…+20!的和。 程式分析 1+2!+3!+…+20!=1+2(1+3(1+4(…20(1)))) res=1 for i in range(20,1,-1): res=i*res+1 print(res) 例項026:遞迴求階乘 題目 利用遞迴方法求5!。 程式分析 遞迴呼叫即可。 def factorial(n): return n*factorial(n-1) if n>1 else 1 print(factorial(5)) 例項027:遞迴輸出 題目 利用遞迴函式呼叫方式,將所輸入的5個字元,以相反順序打印出來。 程式分析 遞迴真是蠢方法。 def rec(string): if len(string)!=1: rec(string[1:]) print(string[0],end='') rec(input('string here:')) 例項028:遞迴求等差數列 題目 有5個人坐在一起,問第五個人多少歲?他說比第4個人大2歲。問第4個人歲數,他說比第3個人大2歲。問第三個人,又說比第2人大兩歲。問第2個人,說比第一個人大兩歲。最後問第一個人,他說是10歲。請問第五個人多大? 程式分析 就一等差數列。 def age(n): if n==1: return 10 return 2+age(n-1) print(age(5)) 例項029:反向輸出 題目 給一個不多於5位的正整數,要求:一、求它是幾位數,二、逆序打印出各位數字。 程式分析 學會分解出每一位數,用字串的方法總是比較省事。 n=int(input('輸入一個正整數:')) n=str(n) print('%d位數'%len(n)) print(n[::-1]) 例項030:迴文數 題目 一個5位數,判斷它是不是迴文數。即12321是迴文數,個位與萬位相同,十位與千位相同。 程式分析 用字串比較方便,就算輸入的不是數字都ok。 n=input("隨便你輸入啥啦:") a=0 b=len(n)-1 flag=True while a<b: if n[a]!=n[b]: print('不是迴文串') flag=False break a,b=a+1,b-1 if flag: print('是迴文串') 例項031:字母識詞 題目 請輸入星期幾的第一個字母來判斷一下是星期幾,如果第一個字母一樣,則繼續判斷第二個字母。 程式分析 這裡用字典的形式直接將對照關係存好。 weekT={'h':'thursday', 'u':'tuesday'} weekS={'a':'saturday', 'u':'sunday'} week={'t':weekT, 's':weekS, 'm':'monday', 'w':'wensday', 'f':'friday'} a=week[str(input('請輸入第一位字母:')).lower()] if a==weekT or a==weekS: print(a[str(input('請輸入第二位字母:')).lower()]) else: print(a) 例項032:反向輸出II 題目 按相反的順序輸出列表的值。 程式分析 無。 a = ['one', 'two', 'three'] print(a[::-1]) 例項033:列表轉字串 題目 按逗號分隔列表。 程式分析 無。 L = [1,2,3,4,5] print(','.join(str(n) for n in L)) 例項034:呼叫函式 題目 練習函式呼叫。 程式分析 無。 def hello(): print('Hello World!') def helloAgain(): for i in range(2): hello() if __name__=='__main__': helloAgain() 例項035:設定輸出顏色 題目 文字顏色設定。 程式分析 無。 class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' print(bcolors.WARNING + "警告的顏色字型?" + bcolors.ENDC) 例項036:算素數 題目 求100之內的素數。 程式分析 用else執行for迴圈的獎勵程式碼(如果for是正常完結,非break)。 lo=int(input('下限:')) hi=int(input('上限:')) for i in range(lo,hi+1): if i > 1: for j in range(2,i): if (i % j) == 0: break else: print(i) 例項037:排序 題目 對10個數進行排序。 程式分析 同例項005。 raw=[] for i in range(10): x=int(input('int%d: '%(i))) raw.append(x) for i in range(len(raw)): for j in range(i,len(raw)): if raw[i]>raw[j]: raw[i],raw[j]=raw[j],raw[i] print(raw) 例項038:矩陣對角線之和 題目 求一個3*3矩陣主對角線元素之和。 程式分析 無。 mat=[[1,2,3], [3,4,5], [4,5,6] ] res=0 for i in range(len(mat)): res+=mat[i][i] print(res) 例項039:有序列表插入元素 題目 有一個已經排好序的陣列。現輸入一個數,要求按原來的規律將它插入陣列中。 程式分析 首先判斷此數是否大於最後一個數,然後再考慮插入中間的數的情況,插入後此元素之後的數,依次後移一個位置。 lis=[1,10,100,1000,10000,100000] n=int(input('insert a number: ')) lis.append(n) for i in range(len(lis)-1): if lis[i]>=n: for j in range(i,len(lis)): lis[j],lis[-1]=lis[-1],lis[j] break print(lis) 例項040:逆序列表 題目 將一個數組逆序輸出。 程式分析 依次交換位置,或者直接呼叫reverse方法。 lis=[1,10,100,1000,10000,100000] for i in range(int(len(lis)/2)): lis[i],lis[len(lis)-1-i]=lis[len(lis)-1-i],lis[i] print('第一種實現:') print(lis) lis=[1,10,100,1000,10000,100000] print('第二種實現:') lis.reverse() print(lis) 例項041:類的方法與變數 題目 模仿靜態變數的用法。 程式分析 構造類,瞭解類的方法與變數。 def dummy(): i=0 print(i) i+=1 class cls: i=0 def dummy(self): print(self.i) self.i+=1 a=cls() for i in range(50): dummy() a.dummy() 例項042:變數作用域 題目 學習使用auto定義變數的用法。 程式分析 python中的變數作用域。 i=0 n=0 def dummy(): i=0 print(i) i+=1 def dummy2(): global n print(n) n+=1 print('函式內部的同名變數') for j in range(20): print(i) dummy() i+=1 print('global宣告同名變數') for k in range(20): print(n) dummy2() n+=10 例項043:作用域、類的方法與變數 題目 模仿靜態變數(static)另一案例。 程式分析 綜合例項041和例項042。 class dummy: num=1 def Num(self): print('class dummy num:',self.num) print('global num: ',num) self.num+=1 n=dummy() num=1 for i in range(5): num*=10 n.Num() 例項044:矩陣相加 題目 計算兩個矩陣相加。 程式分析 建立一個新的矩陣,使用 for 迭代並取出 X 和 Y 矩陣中對應位置的值,相加後放到新矩陣的對應位置中。 X = [[12,7,3], [4 ,5,6], [7 ,8,9]] Y = [[5,8,1], [6,7,3], [4,5,9]] res=[[0,0,0], [0,0,0], [0,0,0]] for i in range(len(res)): for j in range(len(res[0])): res[i][j]=X[i][j]+Y[i][j] print(res) 例項045:求和 題目 統計 1 到 100 之和。 程式分析 無 res=0 for i in range(1,101): res+=i print(res) 例項046:打破迴圈 題目 求輸入數字的平方,如果平方運算後小於 50 則退出。 程式分析 無 while True: try: n=float(input('輸入一個數字:')) except: print('輸入錯誤') continue dn=n**2 print('其平方為:',dn) if dn<50: print('平方小於50,退出') break 例項047:函式交換變數 題目 兩個變數值用函式互換。 程式分析 無 def exc(a,b): return (b,a) a=0 b=10 a,b=exc(a,b) print(a,b) 例項048:數字比大小 題目 數字比較。 程式分析 無 a=int(input('a=')) b=int(input('b=')) if a<b: print('a<b') elif a>b: print('a>b') else: print('a=b') 例項049:lambda 題目 使用lambda來建立匿名函式。 程式分析 無 Max=lambda x,y:x*(x>=y)+y*(y>x) Min=lambda x,y:x*(x<=y)+y*(y<x) a=int(input('1:')) b=int(input('2:')) print(Max(a,b)) print(Min(a,b)) 例項050:隨機數 題目 輸出一個隨機數。 程式分析 使用 random 模組。 import random print(random.uniform(10,20)) 例項051:按位與 題目 學習使用按位與 & 。 程式分析 0&0=0; 0&1=0; 1&0=0; 1&1=1。 a=0o77 print(a) b=a&3 print(b) b=b&7 print(b) 例項052:按位或 題目 學習使用按位或 | 。 程式分析 0|0=0; 0|1=1; 1|0=1; 1|1=1 a=0o77 print(a|3) print(a|3|7) 例項053:按位異或 題目 學習使用按位異或 ^ 。 程式分析 0^0=0; 0^1=1; 1^0=1; 1^1=0 a=0o77 print(a^3) print(a^3^7) 例項054:位取反、位移動 題目 取一個整數a從右端開始的4~7位。 程式分析 可以這樣考慮: (1)先使a右移4位。 (2)設定一個低4位全為1,其餘全為0的數。可用(0<<4) (3)將上面二者進行&運算。 a=int(input('輸入一個數字: ')) b=0 # 0 b=~b # 1 b=b<<4 # 10000 b=~b # 1111 c=a>>4 d=c&b print('a:',bin(a)) print('b:',bin(b)) print('c:',bin(c)) print('d:',bin(d)) 例項055:按位取反 題目 學習使用按位取反~。 程式分析 ~0=1; ~1=0; print(~234) print(~~234) 例項056:畫圈 題目 畫圖,學用circle畫圓形。 程式分析 無。 from tkinter import * canvas=Canvas(width=800,height=600,bg='yellow') canvas.pack(expand=YES,fill=BOTH) k=1 j=1 for i in range(26): canvas.create_oval(310-k,250-k,310+k,250+k,width=1) k+=j j+=0.3 mainloop() 例項057:畫線 題目 畫圖,學用line畫直線。 程式分析 無。 if __name__ == '__main__': from tkinter import * canvas = Canvas(width=300, height=300, bg='green') canvas.pack(expand=YES, fill=BOTH) x0 = 263 y0 = 263 y1 = 275 x1 = 275 for i in range(19): canvas.create_line(x0,y0,x0,y1, width=1, fill='red') x0 = x0 - 5 y0 = y0 - 5 x1 = x1 + 5 y1 = y1 + 5 x0 = 263 y1 = 275 y0 = 263 for i in range(21): canvas.create_line(x0,y0,x0,y1,fill = 'red') x0 += 5 y0 += 5 y1 += 5 mainloop() 例項058:畫矩形 題目 畫圖,學用rectangle畫方形。 程式分析 無。 if __name__ == '__main__': from tkinter import * root = Tk() root.title('Canvas') canvas = Canvas(root,width = 400,height = 400,bg = 'yellow') x0 = 263 y0 = 263 y1 = 275 x1 = 275 for i in range(19): canvas.create_rectangle(x0,y0,x1,y1) x0 -= 5 y0 -= 5 x1 += 5 y1 += 5 canvas.pack() root.mainloop() 例項059:畫圖(醜) 題目 畫圖,綜合例子。 程式分析 醜。 if __name__ == '__main__': from tkinter import * canvas = Canvas(width = 300,height = 300,bg = 'green') canvas.pack(expand = YES,fill = BOTH) x0 = 150 y0 = 100 canvas.create_oval(x0 - 10,y0 - 10,x0 + 10,y0 + 10) canvas.create_oval(x0 - 20,y0 - 20,x0 + 20,y0 + 20) canvas.create_oval(x0 - 50,y0 - 50,x0 + 50,y0 + 50) import math B = 0.809 for i in range(16): a = 2 * math.pi / 16 * i x = math.ceil(x0 + 48 * math.cos(a)) y = math.ceil(y0 + 48 * math.sin(a) * B) canvas.create_line(x0,y0,x,y,fill = 'red') canvas.create_oval(x0 - 60,y0 - 60,x0 + 60,y0 + 60) for k in range(501): for i in range(17): a = (2 * math.pi / 16) * i + (2 * math.pi / 180) * k x = math.ceil(x0 + 48 * math.cos(a)) y = math.ceil(y0 + 48 + math.sin(a) * B) canvas.create_line(x0,y0,x,y,fill = 'red') for j in range(51): a = (2 * math.pi / 16) * i + (2* math.pi / 180) * k - 1 x = math.ceil(x0 + 48 * math.cos(a)) y = math.ceil(y0 + 48 * math.sin(a) * B) canvas.create_line(x0,y0,x,y,fill = 'red') mainloop() 例項060:字串長度 題目 計算字串長度。 程式分析 無。 s='zhangguang101' print(len(s)) 例項061:楊輝三角 題目 打印出楊輝三角形前十行。 程式分析 無。 def generate(numRows): r = [[1]] for i in range(1,numRows): r.append(list(map(lambda x,y:x+y, [0]+r[-1],r[-1]+[0]))) return r[:numRows] a=generate(10) for i in a: print(i) 例項062:查詢字串 題目 查詢字串。 程式分析 無。 s1='aabbxuebixuebi' s2='ab' s3='xue' print(s1.find(s2)) print(s1.find(s3)) 例項063:畫橢圓 題目 畫橢圓。 程式分析 使用 tkinter。 if __name__ == '__main__': from tkinter import * x = 360 y = 160 top = y - 30 bottom = y - 30 canvas = Canvas(width = 400,height = 600,bg = 'white') for i in range(20): canvas.create_oval(250 - top,250 - bottom,250 + top,250 + bottom) top -= 5 bottom += 5 canvas.pack() mainloop() 例項064:畫橢圓、矩形 題目 利用ellipse 和 rectangle 畫圖。。 程式分析 無。 if __name__ == '__main__': from tkinter import * canvas = Canvas(width = 400,height = 600,bg = 'white') left = 20 right = 50 top = 50 num = 15 for i in range(num): canvas.create_oval(250 - right,250 - left,250 + right,250 + left) canvas.create_oval(250 - 20,250 - top,250 + 20,250 + top) canvas.create_rectangle(20 - 2 * i,20 - 2 * i,10 * (i + 2),10 * ( i + 2)) right += 5 left += 5 top += 10 canvas.pack() mainloop() 例項065:畫組合圖形 題目 一個最優美的圖案。 程式分析 無。 import math from tkinter import * class PTS: def __init__(self): self.x = 0 self.y = 0 points = [] def LineToDemo(): screenx = 400 screeny = 400 canvas = Canvas(width = screenx,height = screeny,bg = 'white') AspectRatio = 0.85 MAXPTS = 15 h = screeny w = screenx xcenter = w / 2 ycenter = h / 2 radius = (h - 30) / (AspectRatio * 2) - 20 step = 360 / MAXPTS angle = 0.0 for i in range(MAXPTS): rads = angle * math.pi / 180.0 p = PTS() p.x = xcenter + int(math.cos(rads) * radius) p.y = ycenter - int(math.sin(rads) * radius * AspectRatio) angle += step points.append(p) canvas.create_oval(xcenter - radius,ycenter - radius, xcenter + radius,ycenter + radius) for i in range(MAXPTS): for j in range(i,MAXPTS): canvas.create_line(points[i].x,points[i].y,points[j].x,points[j].y) canvas.pack() mainloop() if __name__ == '__main__': LineToDemo() 例項066:三數排序 題目 輸入3個數a,b,c,按大小順序輸出。 程式分析 同例項005。 raw=[] for i in range(3): x=int(input('int%d: '%(i))) raw.append(x) for i in range(len(raw)): for j in range(i,len(raw)): if raw[i]>raw[j]: raw[i],raw[j]=raw[j],raw[i] print(raw) raw2=[] for i in range(3): x=int(input('int%d: '%(i))) raw2.append(x) print(sorted(raw2)) 例項067:交換位置 題目 輸入陣列,最大的與第一個元素交換,最小的與最後一個元素交換,輸出陣列。 程式分析 無。 li=[3,2,5,7,8,1,5] li[-1],li[li.index(min(li))]=li[li.index(min(li))],li[-1] m=li[0] ind=li.index(max(li)) li[0]=li[ind] li[ind]=m print(li) 例項068:旋轉數列 題目 有n個整數,使其前面各數順序向後移m個位置,最後m個數變成最前面的m個數 程式分析 無。 from collections import * li=[1,2,3,4,5,6,7,8,9] deq=deque(li,maxlen=len(li)) print(li) deq.rotate(int(input('rotate:'))) print(list(deq)) 例項069:報數 題目 有n個人圍成一圈,順序排號。從第一個人開始報數(從1到3報數),凡報到3的人退出圈子,問最後留下的是原來第幾號的那位。 程式分析 無。 if __name__ == '__main__': nmax = 50 n = int(input('請輸入總人數:')) num = [] for i in range(n): num.append(i + 1) i = 0 k = 0 m = 0 while m < n - 1: if num[i] != 0 : k += 1 if k == 3: num[i] = 0 k = 0 m += 1 i += 1 if i == n : i = 0 i = 0 while num[i] == 0: i += 1 print(num[i]) 例項070:字串長度II 題目 寫一個函式,求一個字串的長度,在main函式中輸入字串,並輸出其長度。 程式分析 無。 def lenofstr(s): return len(s) print(lenofstr('tanxiaofengsheng')) 例項071:輸入和輸出 題目 編寫input()和output()函式輸入,輸出5個學生的資料記錄。 程式分析 無。 N = 3 #stu #num : string #name : string #score[4]: list student = [] for i in range(5): student.append(['','',[]]) def input_stu(stu): for i in range(N): stu[i][0] = input('input student num:\n') stu[i][1] = input('input student name:\n') for j in range(3): stu[i][2].append(int(input('score:\n'))) def output_stu(stu): for i in range(N): print ('%-6s%-10s' % ( stu[i][0],stu[i][1] )) for j in range(3): print ('%-8d' % stu[i][2][j]) if __name__ == '__main__': input_stu(student) print (student) output_stu(student) 例項072:建立連結串列 題目 建立一個連結串列。 程式分析 原文不太靠譜。 class Node: def __init__(self, data): self.data = data self.next = None def get_data(self): return self.data class List: def __init__(self, head): self.head = head def is_empty(self): return self.get_len() == 0 def get_len(self): length = 0 temp = self.head while temp is not None: length += 1 temp = temp.next return length def append(self, node): temp = self.head while temp.next is not None: temp = temp.next temp.next = node def delete(self, index): if index < 1 or index > self.get_len(): print("給定位置不合理") return if index == 1: self.head = self.head.next return temp = self.head cur_pos = 0 while temp is not None: cur_pos += 1 if cur_pos == index-1: temp.next = temp.next.next temp = temp.next def insert(self, pos, node): if pos < 1 or pos > self.get_len(): print("插入結點位置不合理") return temp = self.head cur_pos = 0 while temp is not Node: cur_pos += 1 if cur_pos == pos-1: node.next = temp.next temp.next =node break temp = temp.next def reverse(self, head): if head is None and head.next is None: return head pre = head cur = head.next while cur is not None: temp = cur.next cur.next = pre pre = cur cur = temp head.next = None return pre def print_list(self, head): init_data = [] while head is not None: init_data.append(head.get_data()) head = head.next return init_data if __name__=='__main__': head=Node('head') link=List(head) for i in range(10): node=Node(i) link.append(node) print(link.print_list(head)) 例項073:反向輸出連結串列 題目 反向輸出一個連結串列。 程式分析 無。 class Node: def __init__(self, data): self.data = data self.next = None def get_data(self): return self.data class List: def __init__(self, head): self.head = head def is_empty(self): return self.get_len() == 0 def get_len(self): length = 0 temp = self.head while temp is not None: length += 1 temp = temp.next return length def append(self, node): temp = self.head while temp.next is not None: temp = temp.next temp.next = node def delete(self, index): if index < 1 or index > self.get_len(): print("給定位置不合理") return if index == 1: self.head = self.head.next return temp = self.head cur_pos = 0 while temp is not None: cur_pos += 1 if cur_pos == index-1: temp.next = temp.next.next temp = temp.next def insert(self, pos, node): if pos < 1 or pos > self.get_len(): print("插入結點位置不合理") return temp = self.head cur_pos = 0 while temp is not Node: cur_pos += 1 if cur_pos == pos-1: node.next = temp.next temp.next =node break temp = temp.next def reverse(self, head): if head is None and head.next is None: return head pre = head cur = head.next while cur is not None: temp = cur.next cur.next = pre pre = cur cur = temp head.next = None return pre def print_list(self, head): init_data = [] while head is not None: init_data.append(head.get_data()) head = head.next return init_data if __name__=='__main__': head=Node('head') link=List(head) for i in range(10): node=Node(i) link.append(node) print(link.print_list(head)) print(link.print_list(link.reverse(head))) 例項074:列表排序、連線 題目 列表排序及連線。 程式分析 排序可使用 sort() 方法,連線可以使用 + 號或 extend() 方法。 a=[2,6,8] b=[7,0,4] a.extend(b) a.sort() print(a) 例項075:不知所云 題目 放鬆一下,算一道簡單的題目。 程式分析 鬼知道是什麼。 if __name__ == '__main__': for i in range(5): n = 0 if i != 1: n += 1 if i == 3: n += 1 if i == 4: n += 1 if i != 4: n += 1 if n == 3: print (64 + i) 例項076:做函式 題目 編寫一個函式,輸入n為偶數時,呼叫函式求1/2+1/4+…+1/n,當輸入n為奇數時,呼叫函式1/1+1/3+…+1/n 程式分析 無。 def peven(n): i = 0 s = 0.0 for i in range(2,n + 1,2): s += 1.0 / i return s def podd(n): s = 0.0 for i in range(1, n + 1,2): s += 1.0 / i return s def dcall(fp,n): s = fp(n) return s if __name__ == '__main__': n = int(input('input a number: ')) if n % 2 == 0: sum = dcall(peven,n) else: sum = dcall(podd,n) print (sum) 例項077:遍歷列表 題目 迴圈輸出列表 程式分析 無。 l=['moyu','niupi','xuecaibichi','shengfaji','42'] for i in range(len(l)): print(l[i]) 例項078:字典 題目 找到年齡最大的人,並輸出。請找出程式中有什麼問題。 程式分析 無。 if __name__ == '__main__': person = {"li":18,"wang":50,"zhang":20,"sun":22} m = 'li' for key in person.keys(): if person[m] < person[key]: m = key print ('%s,%d' % (m,person[m])) 例項079:字串排序 題目 字串排序。 程式分析 無。 l=['baaa','aaab','aaba','aaaa','abaa'] l.sort() print(l) 例項080:猴子分桃 題目 海灘上有一堆桃子,五隻猴子來分。第一隻猴子把這堆桃子平均分為五份,多了一個,這隻猴子把多的一個扔入海中,拿走了一份。第二隻猴子把剩下的桃子又平均分成五份,又多了一個,它同樣把多的一個扔入海中,拿走了一份,第三、第四、第五隻猴子都是這樣做的,問海灘上原來最少有多少個桃子? 程式分析 無。 if __name__ == '__main__': i = 0 j = 1 x = 0 while (i < 5) : x = 4 * j for i in range(0,5) : if(x%4 != 0) : break else : i += 1 x = (x/4) * 5 +1 j += 1 print(x) for p in range(5): x=(x-1)/5*4 print(x) 例項081:求未知數 題目 809*??=800*??+9*?? 其中??代表的兩位數, 809*??為四位數,8*??的結果為兩位數,9*??的結果為3位數。求??代表的兩位數,及809*??後的結果。 程式分析 無。 a = 809 for i in range(10,100): b = i * a if b >= 1000 and b <= 10000 and 8 * i < 100 and 9 * i >= 100: print(b,' = 800 * ', i, ' + 9 * ', i) for i in range(10,100): if 8*i>99 or 9*i<100: continue if 809*i==800*i+9*i: print(i) break 例項082:八進位制轉十進位制 題目 八進位制轉換為十進位制 程式分析 無。 n=eval('0o'+str(int(input('八進位制輸入:')))) print(n) 例項083:製作奇數 題目 求0—7所能組成的奇數個數。 程式分析 組成1位數是4個。1,3,5,7結尾 組成2位數是7*4個。第一位不能為0 組成3位數是784個。中間隨意 組成4位數是788*4個。 if __name__ == '__main__': sum = 4 s = 4 for j in range(2,9): print (sum) if j <= 2: s *= 7 else: s *= 8 sum += s print('sum = %d' % sum) 例項084:連線字串 題目 連線字串。 程式分析 無。 delimiter = ',' mylist = ['Brazil', 'Russia', 'India', 'China'] print(delimiter.join(mylist)) 例項085:整除 題目 輸入一個奇數,然後判斷最少幾個 9 除於該數的結果為整數。 程式分析 999999 / 13 = 76923。 if __name__ == '__main__': zi = int(input('輸入一個數字:')) n1 = 1 c9 = 1 m9 = 9 sum = 9 while n1 != 0: if sum % zi == 0: n1 = 0 else: m9 *= 10 sum += m9 c9 += 1 print ('%d 個 9 可以被 %d 整除 : %d' % (c9,zi,sum)) r = sum / zi print ('%d / %d = %d' % (sum,zi,r)) 例項086:連線字串II 題目 兩個字串連線程式。 程式分析 無。 a='guangtou' b='feipang' print(b+a) 例項087:訪問類成員 題目 回答結果(結構體變數傳遞)。 程式分析 無。 if __name__ == '__main__': class student: x = 0 c = 0 def f(stu): stu.x = 20 stu.c = 'c' a= student() a.x = 3 a.c = 'a' f(a) print(a.x,a.c) 例項088:列印星號 題目 讀取7個數(1—50)的整數值,每讀取一個值,程式打印出該值個數的*。 程式分析 無。 for i in range(3): print('*'*int(input('input a number: '))) 例項089:解碼 題目 某個公司採用公用電話傳遞資料,資料是四位的整數,在傳遞過程中是加密的,加密規則如下:每位數字都加上5,然後用和除以10的餘數代替該數字,再將第一位和第四位交換,第二位和第三位交換。 程式分析 無。 n=input() n = str(n) a=[] for i in range(4): a.append(int(n[i])+5) a[0],a[3]=a[3],a[0] a[1],a[2]=a[2],a[1] print ("".join('%s' %s for s in a)) 例項090:列表詳解 題目 列表使用例項。 程式分析 無。 #list #新建列表 testList=[10086,'中國移動',[1,2,4,5]] #訪問列表長度 print (len(testList) ) #到列表結尾 print (testList[1:]) #向列表新增元素 testList.append('i\'m new here!') print (len(testList) ) print (testList[-1] ) #彈出列表的最後一個元素 print (testList.pop(1) ) print (len(testList) ) print (testList ) st comprehension #後面有介紹,暫時掠過 matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] print (matrix ) print (matrix[1] ) col2 = [row[1] for row in matrix]#get a column from a matrix print (col2 ) col2even = [row[1] for row in matrix if row[1] % 2 == 0]#filter odd item print (col2even) 例項091:time模組 題目 時間函式舉例1。 程式分析 無。 if __name__ == '__main__': import time print (time.ctime(time.time())) print (time.asctime(time.localtime(time.time()))) print (time.asctime(time.gmtime(time.time()))) 例項092:time模組II 題目 時間函式舉例2。 程式分析 如何浪費時間。 if __name__ == '__main__': import time start = time.time() for i in range(3000): print(i) end = time.time() print (end - start) 例項093:time模組III 題目 時間函式舉例3。 程式分析 如何浪費時間。 if __name__ == '__main__': import time start = time.clock() for i in range(100): print(i) end = time.clock() print('different is %6.3f' % (end - start)) 例項094:time模組IV 題目 時間函式舉例4。 程式分析 如何浪費時間。 if __name__ == '__main__': import time import random play_it = input('do you want to play it.(\'y\' or \'n\')') while play_it == 'y': c = input('input a character:\n') i = random.randint(0,2**32) % 100 print ('please input number you guess:\n') start = time.clock() a = time.time() guess = int(input('input your guess:\n')) while guess != i: if guess > i: print('please input a little smaller') guess = int(input('input your guess:\n')) else: print('please input a little bigger') guess = int(input('input your guess:\n')) end = time.clock() b = time.time() var = (end - start) / 18.2 print (var) # print 'It took you %6.3 seconds' % time.difftime(b,a)) if var < 15: print ('you are very clever!') elif var < 25: print ('you are normal!') else: print ('you are stupid!') print ('Congradulations') print ('The number you guess is %d' % i) play_it = input('do you want to play it.') 例項095:轉換時間格式 題目 字串日期轉換為易讀的日期格式。 程式分析 看看就得了,dateutil是個第三方庫。 from dateutil import parser dt = parser.parse("Aug 28 2015 12:00AM") print (dt) 例項096:計算復讀次數 題目 計算字串中子串出現的次數。 程式分析 無。 s1='xuebixuebixuebixuebixuebixuebixuebixue' s2='xuebi' print(s1.count(s2)) 例項097:磁碟寫入 題目 從鍵盤輸入一些字元,逐個把它們寫到磁碟檔案上,直到輸入一個 # 為止。 程式分析 無。 if __name__ == '__main__': from sys import stdout filename = input('輸入檔名:\n') fp = open(filename,"w") ch = input('輸入字串:\n') while ch != '#': fp.write(ch) stdout.write(ch) ch = input('') fp.close() 例項098:磁碟寫入II 題目 從鍵盤輸入一個字串,將小寫字母全部轉換成大寫字母,然後輸出到一個磁碟檔案"test"中儲存。 程式分析 無。 if __name__ == '__main__': fp = open('test.txt','w') string = input('please input a string:\n') string = string.upper() fp.write(string) fp = open('test.txt','r') print (fp.read()) fp.close() 例項099:磁碟讀寫 題目 有兩個磁碟檔案A和B,各存放一行字母,要求把這兩個檔案中的資訊合併(按字母順序排列), 輸出到一個新檔案C中。 程式分析 無。 if __name__ == '__main__': import string fp = open('test1.txt') a = fp.read() fp.close() fp = open('test2.txt') b = fp.read() fp.close() fp = open('test3.txt','w') l = list(a + b) l.sort() s = '' s = s.join(l) fp.write(s) fp.close() 例項100:列表轉字典 題目 列表轉換為字典。 程式分析 無。 i = ['a', 'b'] l = [1, 2] print (dict(zip(i,l)))
&n
版权声明
本文为[itread01]所创,转载请带上原文链接,感谢
https://www.itread01.com/content/1604668087.html
边栏推荐
- Linked blocking Queue Analysis of blocking queue
- 5.5 controlleradvice notes - SSM in depth analysis and project practice
- The difference between gbdt and XGB, and the mathematical derivation of gradient descent method and Newton method
- Windows 10 tensorflow (2) regression analysis of principles, deep learning framework (gradient descent method to solve regression parameters)
- How to customize sorting for pandas dataframe
- I'm afraid that the spread sequence calculation of arbitrage strategy is not as simple as you think
- Custom function form of pychar shortcut key
- 【自学unity2d传奇游戏开发】如何让角色动起来
- 一篇文章带你了解CSS 渐变知识
- 仅用六种字符来完成Hello World,你能做到吗?
猜你喜欢
给字节的学姐讲如何准备“系统设计面试”
C + + and C + + programmers are about to be eliminated from the market
A course on word embedding
It's easy to operate. ThreadLocal can also be used as a cache
游戏主题音乐对游戏的作用
教你轻松搞懂vue-codemirror的基本用法:主要实现代码编辑、验证提示、代码格式化
If PPT is drawn like this, can the defense of work report be passed?
一篇文章带你了解CSS3 背景知识
Wow, elasticsearch multi field weight sorting can play like this
Unity性能优化整理
随机推荐
FastThreadLocal 是什么鬼?吊打 ThreadLocal 的存在!!
Building and visualizing decision tree with Python
html+vue.js 實現分頁可相容IE
It's easy to operate. ThreadLocal can also be used as a cache
ES6学习笔记(二):教你玩转类的继承和类的对象
The choice of enterprise database is usually decided by the system architect - the newstack
前端都应懂的入门基础-github基础
It is really necessary to build a distributed ID generation service
Analysis of partial source codes of qthread
The dynamic thread pool in Kitty supports Nacos and Apollo multi configuration centers
Basic principle and application of iptables
Classical dynamic programming: complete knapsack problem
ES6学习笔记(四):教你轻松搞懂ES6的新增语法
Brief introduction and advantages and disadvantages of deepwalk model
Chainlink brings us election results into blockchain everipedia
Our best practices for writing react components
Elasticsearch数据库 | Elasticsearch-7.5.0应用搭建实战
Analysis of etcd core mechanism
[actual combat of flutter] pubspec.yaml Configuration file details
electron 實現檔案下載管理器