1. 程式人生 > >Python教程--廖雪峰練習參考彙總(一)

Python教程--廖雪峰練習參考彙總(一)

題源:廖老師的官網
小生全是為了方便後期程式碼整理,從多篇大佬中的文章引用了程式碼,如有冒犯之處,請聯絡小生。

練習
小明的成績從去年的72分提升到了今年的85分,請計算小明成績提升的百分點,並用字串格式化顯示出’xx.x%’,只保留小數點後1位:

# -*- coding: utf-8 -*-
s1 = 72
s2 = 85
r = 100*(s2-s1)/s1
print('提高了''%.1f%%' % r)

練習
小明身高1.75,體重80.5kg。請根據BMI公式(體重除以身高的平方)幫小明計算他的BMI指數,並根據BMI指數:
低於18.5:過輕
18.5-25:正常
25-28:過重
28-32:肥胖
高於32:嚴重肥胖
用if-elif判斷並列印結果:

# -*- coding: utf-8 -*-

height = 1.75
weight = 80.5bmi = weight / height / height    
if bmi < 18.5:  
    print ('過輕')  
elif bmi >= 18.5 and bmi < 25:  
    print ('正常')  
elif bmi >= 25 and bmi < 28:  
    print ('過重')  
elif bmi >= 28 and bmi <32:  
    print ('肥胖')  
else
: print ('嚴重肥胖')

練習
請利用迴圈依次對list中的每個名字打印出Hello, xxx!:

# -*- coding: utf-8 -*-
L = ['Bart', 'Lisa', 'Adam']
for i in L:
    print('Hello,',i,'!')

練習
請利用Python內建的hex()函式把一個整數轉換成十六進位制表示的字串:

# -*- coding: utf-8 -*-

n1 = 255
n2 = 1000
print(hex(n1))
print(hex(n2))

練習
請定義一個函式quadratic(a, b, c),接收3個引數,返回一元二次方程:
ax2 + bx + c = 0
的兩個解。
提示:計算平方根可以呼叫math.sqrt()函式。

# -*- coding: utf-8 -*-
import math
def quadratic(a, b, c):
    L=((-b+math.sqrt(b*b-4*a*c))/(2*a),(-b-math.sqrt(b*b-4*a*c))/(2*a))
    return L

# 測試:
print('quadratic(2, 3, 1) =', quadratic(2, 3, 1))
print('quadratic(1, 3, -4) =', quadratic(1, 3, -4))

if quadratic(2, 3, 1) != (-0.5, -1.0):
    print('測試失敗')
elif quadratic(1, 3, -4) != (1.0, -4.0):
    print('測試失敗')
else:
    print('測試成功')

練習
以下函式允許計算兩個數的乘積,請稍加改造,變成可接收一個或多個數並計算乘積:
【轉】

# -*- coding: utf-8 -*-
def product(*numbers):                                              #定義一個函式
    if numbers is None or len(numbers)<=0 :
        raise TypeError("args not null!")                              #將函式提前給定好各種情況,如果小於零,等於零或者未輸入
    sum = 1
    for n in numbers:
        sum = sum *n                            #如果n在給定的數列中,那麼就將sum*每一個數值得出總數
    return sum
# 測試
print('product(5) =', product(5))
print('product(5, 6) =', product(5, 6))
print('product(5, 6, 7) =', product(5, 6, 7))
print('product(5, 6, 7, 9) =', product(5, 6, 7, 9))
if product(5) != 5:
    print('測試失敗!')
elif product(5, 6) != 30:
    print('測試失敗!')
elif product(5, 6, 7) != 210:
    print('測試失敗!')
elif product(5, 6, 7, 9) != 1890:
    print('測試失敗!')
else:
    try:
        product()
        print('測試失敗!')
    except TypeError:
        print('測試成功!')

練習
漢諾塔的移動可以用遞迴函式非常簡單地實現。
請編寫move(n, a, b, c)函式,它接收引數n,表示3個柱子A、B、C中第1個柱子A的盤子數量,然後打印出把所有盤子從A藉助B移動到C的方法,例如:

# -*- coding: utf-8 -*-
def move(n, a, b, c):
    if n == 1:
       print('move', a, '-->', c)
    else:
       move(n-1, a, c, b) 
       move(1, a, b, c) 
       move(n-1, b, a, c) 
# 期待輸出:
# A --> C
# A --> B
# C --> B
# A --> C
# B --> A
# B --> C
# A --> C
move(3, 'A', 'B', 'C')

練習
利用切片操作,實現一個trim()函式,去除字串首尾的空格,注意不要呼叫str的strip()方法:

# -*- coding: utf-8 -*-
def trim(s):
    if len(s) == 0:
        return s
    elif s[0] == ' ':
        return (trim(s[1:]))
    elif s[-1] == ' ':
        return (trim(s[:-1]))
    return s

# 測試:
if trim('hello  ') != 'hello':
    print('測試失敗!')
elif trim('  hello') != 'hello':
    print('測試失敗!')
elif trim('  hello  ') != 'hello':
    print('測試失敗!')
elif trim('  hello  world  ') != 'hello  world':
    print('測試失敗!')
elif trim('') != '':
    print('測試失敗!')
elif trim('    ') != '':
    print('測試失敗!')
else:
    print('測試成功!')

練習–迭代
請使用迭代查詢一個list中最小和最大值,並返回一個tuple:【轉 忘了哪位的了~】

def trim(s):
    #'''首先判斷該字串是否為空,如果為空,就返回該字串,
    #如果不為空的話,就判斷字串首尾字元是否為空,
    #如果為空,就使用遞迴再次呼叫該函式trim(),否則就返回該函式'''
    if len(s) == 0:
        return s
    elif s[0] == ' ':
        return (trim(s[1:]))
    elif s[-1] == ' ':
        return (trim(s[:-1]))
    return s


# 測試
if findMinAndMax([]) != (None, None):
    print('測試失敗!')
elif findMinAndMax([7]) != (7, 7):
    print('測試失敗!')
elif findMinAndMax([7, 1]) != (1, 7):
    print('測試失敗!')
elif findMinAndMax([7, 1, 3, 9, 5]) != (1, 9):
    print('測試失敗!')
else:
    print('測試成功!')

練習
如果list中既包含字串,又包含整數,由於非字串型別沒有lower()方法,所以列表生成式會報錯:


>>> L = ['Hello', 'World', 18, 'Apple', None]
>>> [s.lower() for s in L]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <listcomp>
AttributeError: 'int' object has no attribute 'lower'

使用內建的isinstance函式可以判斷一個變數是不是字串:

>>> x = 'abc'
>>> y = 123
>>> isinstance(x, str)
True
>>> isinstance(y, str)
False

請修改列表生成式,通過新增if語句保證列表生成式能正確地執行:

# -*- coding: utf-8 -*-
L1 = ['Hello', 'World', 18, 'Apple', None]
L2=[]
for i in L1:
    if isinstance(i,str)==True:
       L2.append(i.lower())

# 測試:
print(L2)
if L2 == ['hello', 'world', 'apple']:
    print('測試通過!')
else:
    print('測試失敗!')

練習
楊輝三角定義如下:這裡寫圖片描述

把每一行看做一個list,試寫一個generator,不斷輸出下一行的list:


# -*- coding: utf-8 -*-
def triangles():
    L = [1]
    while True:     
        yield L[:len(L)]
        L.append(0) 
        L = [L[i - 1] + L[i] for i in range(len(L))]

def main():
    n = 0
    results = []
    for x in triangles():
        print(x)
        results.append(x)
        n = n + 1
        if n == 10:
            break

    if results == [
        [1],
        [1, 1],
        [1, 2, 1],
        [1, 3, 3, 1],
        [1, 4, 6, 4, 1],
        [1, 5, 10, 10, 5, 1],
        [1, 6, 15, 20, 15, 6, 1],
        [1, 7, 21, 35, 35, 21, 7, 1],
        [1, 8, 28, 56, 70, 56, 28, 8, 1],
        [1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
    ]:
        print("測試成功!")
    else:
        print("測試失敗!")

    for y in results:
        print(y)

main()

練習
利用map()函式,把使用者輸入的不規範的英文名字,變為首字母大寫,其他小寫的規範名字。輸入:[‘adam’, ‘LISA’, ‘barT’],輸出:[‘Adam’, ‘Lisa’, ‘Bart’]:

# -*- coding: utf-8 -*-
def normalize(name): 
     return "%s" % (inStr[:1].upper() + inStr[1:].lower())

#來自 <https://www.cnblogs.com/bjdxy/archive/2012/11/22/2783107.html> 

# 測試:
L1 = ['adam', 'LISA', 'barT']
L2 = list(map(normalize, L1))
print(L2)

Python提供的sum()函式可以接受一個list並求和,請編寫一個prod()函式,可以接受一個list並利用reduce()求積:

# -*- coding: utf-8 -*-
from functools import reduce
def prod(L): 

      return reduce(lambda x, y: x*y, L)

#來自 <https://www.cnblogs.com/taoleilei/articles/5461635.html> 

print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9]))
if prod([3, 5, 7, 9]) == 945:
    print('測試成功!')
else:
    print('測試失敗!')

利用map和reduce編寫一個str2float函式,把字串’123.456’轉換成浮點數123.456

# -*- coding: utf-8 -*-
# [轉](https://blog.csdn.net/alicegotoanother/article/details/79066040)
from functools import reduce
def str2float(s):
    def str2num(s):  
        return {'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9}[s]  
    def fnMuti(x,y):  
        return x*10 + y  
    def fnDivid(x,y):  
        return x/10 + y  
    dotIndex = s.index('.')  
    return reduce(fnMuti,map(str2num,s[:dotIndex])) + reduce(fnDivid,list(map(str2num,s[dotIndex+1:]))[::-1])/10  
print('str2float(\'123.456\') =', str2float('123.456'))
if abs(str2float('123.456') - 123.456) < 0.00001:
    print('測試成功!')
else:
    print('測試失敗!')