python实践第5章-函数和lambda表达式

1.定义一个函数,该函数可接收一个 list 作为参数,该函数使用直接选择排序对 list排序
def ssort(list):
    lens=len(list)
    for i in range(lens):
        min=i
        for j in range(i,lens):
            if list[min]>list[j]:
                min=j
        list[i],list[min]=list[min],list[i]
list1=[23,12,66,90,25,3]
ssort(list1)
print(list1)
[3, 12, 23, 25, 66, 90]
2.定义一个函数,该函数可接收一个 list 作为参数,该函数使用冒泡排序对 list排序
def bsort(list):
    lens=len(list)
    for i in range(lens):
        for j in range(0,lens-i-1):
            if list[j]>list[j+1]:
                list[j],list[j+1]=list[j+1],list[j]
list2=[23,12,66,90,25,3] 
bsort(list2)
print(list2)
[3, 12, 23, 25, 66, 90]
3.定义一个 is leap(year 函数,该函数可判断 yea1 是否为闰年。若是闰年,则返回 True ;否则返回 False
def is_leap(year):
    if year%100!=0 and year%4==0 or year%400==0:
        return True
    else:
        return False
print(is_leap(2004))
print(is_leap(2019))
True
False
4.定义一个 ount_str_ char( my_ st1 )函数,该函数返回参数字符串中包含多少个数字、 少个英文字母、多少个空白字符、多少个其他字符
def count_str_char(my_str):
    a,b,c,d=0,0,0,0
    for i in my_str:
        if i.isdigit():
            a+=1
        elif i.isalpha():
            b+=1
        elif i.isspace():
            c+=1
        else:
            d+=1
    print('数字:',a,'英文字母:',b,'空白字符:',c,'其他字符:',d)
str1 = 'dhgs%  jjji126gfd5'
count_str_char(str1)
数字: 4 英文字母: 11 空白字符: 2 其他字符: 1
5.定义 fn(n)函数,该函数返回1到n的立方和
def fn(n):
    sum=0
    for i in range(n+1):
        sum+=i*i*i
    return sum
print(fn(1))
print(fn(2))
print(fn(3))
print(fn(4))
1
9
36
100
6.定义 fn(n )函数,该函数返回n的阶乘
def fn(n):
    if n==0:
        return 1
    else:
        return n*fn(n-1)
fn(3)
            
6
7.定义一个函数,该函数可接收 list 作为参数,该函数用于去除 list 中重复的元素
def fn(list):
    temp=[]
    for i in list:
        if i not in temp:
            temp.append(i)
    return temp
list3=[7,7,'l','l','o','#']
print(fn(list3))
[7, 'l', 'o', '#']
8.定义 fn(n)函数,该函数返回一个包含n个不重复的0~100之间整数的元组
import random
def fn(n):
    temp=[]
    for i in range(n):
        num = int(random.randint(0,100))
        if num not in temp:
            temp.append(num)
    return tuple(temp)
print(fn(15))
(64, 19, 93, 57, 91, 10, 5, 98, 74, 14, 94, 85, 89, 36, 34)
9.定义 fn(n)函数,该函数返回一个包含n个不重复的大写字母的元组
def fn(n):
    temp=[]
    for i in range(n):
        ch=chr(random.randint(65,91))
        if ch not in temp:
            temp.append(ch)
    return tuple(temp)
print(fn(8))
('S', 'Q', 'R', 'G', 'C', 'Z')
10.定义 fn(n)函数,其中n表示输入n行n列的矩阵(数的方阵)。在输出时,先输出n行n列的矩阵,再输出该矩阵的转置形式
def fn(n):
    matrix=[i for i in range(1,n*n+1)]
    for i in range(n):
        for j in range(n):
            print(matrix[i*n+j],end=' ')
        print('')
    print('------------')
    for i in range(n):
        for j in range(n):
            print(matrix[j*n+i],end=' ')
        print('')
fn(3)
1 2 3 
4 5 6 
7 8 9 
------------
1 4 7 
2 5 8 
3 6 9 

你可能感兴趣的:(python,开发语言)