Python小課題練習作業


作業一:                                                                                                                        

利用*字典*輸出目錄,可以選擇目錄進入,可以回退、退出!

#conding:utf8


menu = {'北京':{'昌平':{'沙河':{'昌平婦幼',}},'海淀':{'海淀一區':{'海淀二區'},}},} #字典嵌套

current_layer = menu #利用此變量來記錄當前的層的位置
pre_menu = [] #用【】來記錄每一層

while True:
for k in current_layer:
print (k)
choice = input('>>>>>>>:').strip() #去除輸入選項連邊的空格
if len(choice) == 0: #通過len的長度來判斷用戶是否輸入了
continue

if choice in current_layer:
pre_menu.append(current_layer)
current_layer = current_layer[choice]
elif choice == 'b':
if len(pre_menu) > 0: #通過大於0 來判斷,還有目錄可退
current_layer = pre_menu.pop() #利用pop來彈出上面的一層。
elif choice == 'q':
exit()

作業二                                                                                                              

list的小練習:實現購物車功能

product_list = [['iphone',6500],['Mobli',5000],['huawei',4000],['oppo',300],['vivo',100]]


money = int(input('please input your money:'))
got_list = []

while True:
for i,v in enumerate(product_list): #顯示二維的數列,0 ... 1.... 2....
print (i,v)
choice_goods = input('which good do you want to get :')

if choice_goods.isdigit(): #判斷是否是輸入的數字
choice_goods = int(choice_goods)
if choice_goods < len(product_list) and choice_goods >=0: #條件判斷,看是否超出范圍
if money > product_list[choice_goods][1]: #如果錢大於物品的價格
money -= product_list[choice_goods][1] #計算余額
got_list.append(product_list[choice_goods][0]) #把買到的商品添加到列表中
print ('you good is %s' %(got_list))
print ('you left money is: %s' %(money))
print ('')
print ('')

else:
print ('you do not have enough money to bu anything!')
print ('\n')

else:
print ('we do not have this good')
print ('\n')

作業三                                                                                                        

冒泡算法小練習

a_list = [9,8,7,6,5,4,3,2,1]

for j in range(len(a_list) -1): #第二步,每次循環排好一個數,則需要len(a_list) -1 次,才能全部的排好
#第一步,初級算法不減j,每次循環都是從頭到尾比較一遍,減去j,后面排好的則不用比較

for i in range(len(a_list)-1 - j):
if a_list[i] > a_list[i+1]: #最大數排到最后面去
a_list[i],a_list[i+1] = a_list[i+1],a_list[i] #利用a,b = b,a 對調

print(a_list)

作業四                                                                                                    

插入算法小練習

實現方法一

a_list = [3 ,66 ,3 ,41 ,34 ,6 ,7 ,845 ,234 ,31]
b_list = [a_list.pop()] #pop會在列表的最后面彈出一個數,並顯示

for num in a_list:
pos = -1 #去查看是通過比較后插入的位置
for i in range(len(b_list)): #用i去獲取下墜
if num <= b_list[i]: #循環比較,去尋找合適的位置
pos = i
b_list.insert(i ,num)
break
if pos == -1:
b_list.append(num)

print (b_list)

實現方法二

arr1 = [10,9,8,7,6,5,4,3,2,1]

for i in range(1, len(arr1)): #從第二個數開始拿來作比較
j = i - 1 #通過j來判斷需要插入的這個數前面有多少個數
while j >= 0: #j最小為0 ,表示只有兩個數做比較
if arr1[j + 1] < arr1[j]:#新那的這個數用j+1表示,
arr1[j],arr1[j + 1] = arr1[j + 1],arr1[j]
j -= 1

print (arr1)

做業五                                                                                                          

打印99乘法表

#! /usr/bin/python
# Filename : table_9x9.py
 
print '\n9x9 Table\n'
 
for i in range(1, 10) :
    for j in range(1, i+1) :
        print j, 'x', i, '=', j*i, '\t',
        # print '%d x %d = %d\t' %(j, i, j*i),
    print '\n'
print '\nDone!'
 
 
關於該程序的說明:
1. 第一行是特殊注釋行,稱為組織行,用來告訴GNU/Linux系統應該使用哪個解釋器來執行該程序。
2. 第二行至第四行都是一般的注釋行,用來說明一些信息的(如文件名,作者,時間等)。
3. 第六行打印一個字符串。
4. 第八行i取值范圍為1, 2, 3, 4, 5, 6, 7, 8, 9
5. 第九行j取值范圍為1, 2, ..., i
6. 第十行和第十一行效果一樣,最后的逗號都是用來取消自動換行的。
7. 第十二行作用是在每個內層for循環結束后換行,即在輸出完九九乘法表一行后換行。
8. 第十四行打印一個字符串。
 
 
小結:通過這個程序熟悉print的用法,for循環的用法,以及range函數的特點。

課堂中提到的方法:

for i in range(1,10):
    output = ''
    for j in range(1,i+1):
        output+= "%s*%s=%2s "%(i,j,i*j)
    print output

 

---------------------------------------------------

作業六:                                                                                                       

取一個列表中前兩位大的數字

 
#!/usr/bin/python

NumList = [1,2,3,2,12,3,1,3,21,2,2,3,4111,22,3333,444,111,4,5,777,4222,46,33,45,65555]

max_num = 0
sec_num = 0

for n in NumList:
if max_num < n:
sec_num=max_num
#獲取最大數之前的比較的哪個數肯定是在這之前第二大的
max_num = n
#但是后面如果再出現比最大的大,比之前比較出料的第二大
#小的數時需要再比較下。
if n < max_num and n > sec_num:
sec_num = n


print ('The bigest NUM is : %s' %(max_num))
print ('The second one is : %s' %(sec_num))
 

利用單循環來同事去除兩個兩個數。

作業七                                                                                                      

二分查找法(利用遞歸函數)

num_list = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,20,21,22]


def erfen(find_num,num):
mid = int(len(num)/2)
if mid ==0: #此處已經到了最后一個數,需要判斷下,返回結果
if num[mid] == find_num:
print("we find it finally",find_num)
else:
print( "we can not find this num in list",find_num)
return #表示此遞歸的結束

if num[mid] == find_num:
print( "We find it",find_num)
elif num[mid] > find_num:
print ("we are going to search in left",num[mid],num[0:mid])
erfen(find_num,num[0:mid])
else:
print ("we are going to serch in right",num[mid],num[mid+1:])
erfen(find_num,num[mid+1:])

erfen(19,num_list)

作業八                                                                                                           

利用函數完成用戶的注冊登錄功能

 

#!/usr/bin/python
#encoding: utf-8

import getpass

user_list = {}

def new_user():
username = raw_input('please input your new name:')
if username in user_list:
print '%s is already exits!!' %username
else:
passwd = getpass.getpass() #已密碼不顯示的方式輸入。
user_list[username] = passwd

def old_user():
username = raw_input('please input your name:')
passwd = raw_input('please input your passwd:')
if username in user_list:
if user_list[username] == passwd:
print 'login successfull!!'
else:
print 'login fail!!'
else:
print 'login fail!!!'

CMD = {'n' : new_user , 'o' : old_user}

def main_menu():
ppp = '''
新用戶注冊:n
老用戶登錄:o
推出:q

'''
while True:
try:
choice = raw_input(ppp)
except (KeyboardInterrupt, EOFError): #捕捉ctrl+ D 的錯誤輸出。
choice = 'q'

if choice not in 'noq':
print 'please input again'
continue
if choice == 'q':
break
CMD[choice]() #通過取字典的key,選擇來執行函數

 

if __name__ == '__main__':
main_menu()

作業九

log日志前十排序,其中包括重復的。利用函數簡單的html輸出

#!/usr/bin/python
#coding:utf8

def openFile(log):
with open(log) as f:
content = f.readlines()
return content

def countLine(fn):
content = fn
count_dict = {}
for line in content:
line = line.split(' ') # string 通過split 轉換為list
local_ip,uri,code = line[0],line[6],line[8]
        #利用元組來作為key,然后統計數量
        count_dict[(local_ip,uri,code)] = count_dict.get((local_ip,uri,code),0) + 1 
    #這個排序的功能網上copy的,不了解原理
    count_dict = sorted(count_dict.items() ,key=lambda item:item[1],reverse=True)        
return count_dict

def detailLine(fn):
count_dict = fn
#下面進行重復行計數為一行。
n = 1 #取行計數
num = 0 #用於判斷'統計數量'是否出現一樣的
# print ('-----IP------------------URI----------CODE---count---')
# for i in count_dict:
# if n <= 10: # 取前十
# if i[1] != num:
# print('%-10s%20s%5s%10s ---->no%s' % (i[0][0], i[0][1], i[0][2], i[1], n))
# num = i[1]
# n += 1
# elif i[1] == num:
# print('%-10s%20s%5s%10s' % (i[0][0], i[0][1], i[0][2], i[1]))

with open('count.html','w') as f:
res = "<table border='1'>"
res += '<tr><td>IP</td><td>URI</td><td>CODE</td><td>COUNT</td></tr>'
for i in count_dict:
if n <= 10:
if i[1] != num:
res += '<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>'% (i[0][0],
i[0][1], i[0][2], i[1])
num = i[1]
n += 1
elif i[1] == num:
res += '<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>' % (i[0][0],
i[0][1], i[0][2], i[1])
res +='</table>'
f.write(res)
def main():
first = openFile('access.log')
second = countLine(first)
detailLine(second)

if __name__ == '__main__':
main()

作業十,

 生成隨機驗證碼:

方法一:
import string,random

source = string.digits + string.ascio_lowercase
print ("".join(random.sample(source,6)))

方法二:
checkcode = ''
for i in range(6):
current = random.randrange(0,6)
if current != i:
temp = chr(random.randint(65,90))
else:
temp = random.randint(0-9)
checkcode += str(temp)
print(checkcode)

 

作業十一

利用快排,來對列表數字進行排序。

a = [ 65,2,1,3,6,1,3,4,1,3,6,7,8243,3]

def kuaipai(arr):
    if len(arr) <= 1:
        return arr
    num = arr.pop() #在列表中pop彈出一個對象來,作為比較的對象,然后列表中就少了這個對象
    left = []
    right = []
    for i in arr: #因為里面已經沒有了需要比較的對象,所以可以直接循環列表來比較。
        if num > i:
            left.append(i)
        else:
            right.append(i)
    return kuaipai(left) + [num] + kuaipai(right) #用到了函數的遞歸

print kuaipai(a)


運行結果:
[1, 1, 1, 2, 3, 3, 3, 3, 4, 6, 6, 7, 65, 8243]

 

 
 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM