day10作業(yè)

1. 編寫函數(shù),求1 + 2 + 3 +…N的和

def sum1(n):
    sumn = 0
    for i in range(1, n+1):
        sumn += i
    return sumn

print(sum1(6))

2. 編寫一個(gè)函數(shù),求多個(gè)數(shù)中的最大值

def max_num(*nums):
    maxnum = 0
    for i in nums:
        if i>maxnum:
            maxnum = i
    return maxnum

print(max_num(1, 2, 3))

3. 編寫一個(gè)函數(shù),實(shí)現(xiàn)搖骰子的功能,打印N個(gè)骰子的點(diǎn)數(shù)和

def roll(n):
    import random
    sum_roll = 0
    for i in range(1, n+1):
        num = random.randint(1, 6)
        print("第%d個(gè)骰子的點(diǎn)數(shù)是:" %i, num)
        sum_roll += num
    print("總的點(diǎn)數(shù)是:", sum_roll)

roll(3)

4. 編寫一個(gè)函數(shù),交換指定字典的key和value。

例如: dict1 = {'a': 1, 'b': 2, 'c': 3} --> dict1 = {1: 'a', 2: 'b', 3: 'c'}

def exchange(dict1):
    for key in dict1:
        value = dict1[key]
        del dict1[key]
        dict1[value] = key

dict1 = {'a': 1, 'b': 2, 'c': 3}
exchange(dict1)

5. 編寫一個(gè)函數(shù),提取指定字符串中所有的字母,然后拼接在一起產(chǎn)生一個(gè)新的字符串

例如: 傳入 '12a&bc12d-+' --> 'abcd'

def wordto_str(str1):
    for i in str1:
        if 'a'<=i<='z' or 'A'<=i<='Z':
            print(i, end='')

wordto_str('12assb#%asd')

6. 寫一個(gè)函數(shù),求多個(gè)數(shù)的平均值

print()
def average(*nums):
    sum_nums = 0
    for i in nums:
        sum_nums += i
    print(sum_nums/len(nums))

average(1, 2, 3, 4, 5)

7. 寫一個(gè)函數(shù),默認(rèn)求10的階乘,也可以求其他數(shù)字的階乘

def rect(n=10):
    sum1 = 1
    for i in range(1, n+1):
        sum1 *= i
    print(sum1)

rect(12)


注意:以下方法不能使用系統(tǒng)提供的方法和函數(shù),全部自己寫邏輯**

8. 寫一個(gè)自己的capitalize函數(shù),能夠?qū)⒅付ㄗ址氖鬃帜缸兂纱髮懽帜?/h1>

例如: 'abc' -> 'Abc' '12asd' --> '12asd'

def capitalize(str1):
    if 'a'<=str1[0]<='z':
        return chr(ord(str1[0])-32)+str1[1:]
    #     print(chr(ord(str1[0])-32), end='')
    #     for i in str1[1:]:
    #         print(i, end='')
    # else:
    #     print(str1)

print(capitalize('abc'))

9. 寫一個(gè)自己的endswith函數(shù),判斷一個(gè)字符串是否以指定的字符串結(jié)束

例如: 字符串1:'abc231ab'
字符串2: 'ab'
函數(shù)結(jié)果為: True
字符串1: 'abc231ab'
字符串2: 'ab1'
函數(shù)結(jié)果為: False

print()
def endswith(str1, str2):
    length2 = len(str2)
    if str1[len(str1)-length2:] == str2: #if str1[-len(str1):] == str2:
        print('True')
    else:
        print('False')

endswith('abc123abc', 'bc')

10. 寫一個(gè)自己的isdigit函數(shù),判斷一個(gè)字符串是否是純數(shù)字字符串

例如:
'1234921' 結(jié)果: True
'23函數(shù)' 結(jié)果: False
'a2390' 結(jié)果: False

def isdigital(str1):
    for i in str1:
        if '0'<=i<='9':
            continue
        else:
            print(False)
            break
    else:
        print(True)

isdigital('1235678')

11. 寫一個(gè)自己的upper函數(shù),將一個(gè)字符串中所有的小寫字母變成大寫字母

例如:
'abH23好rp1' 結(jié)果: 'ABH23好RP1'

def upper(str1):
    for i in str1:
        if 'a'<=i<='z':
            i = chr(ord(i)-32)
        print(i, end='')

upper('asq24hio')

12.寫一個(gè)自己的rjust函數(shù),創(chuàng)建一個(gè)字符串的長(zhǎng)度是指定長(zhǎng)度,原字符串在新字符串中右對(duì)齊,剩下的部分用指定的字符填充

例如:
原字符:'abc'
寬度: 7
字符: '^'
結(jié)果: '^^^^abc'
原字符: '你好嗎'
寬度: 5
字符: '0'
結(jié)果: '00你好嗎'

def rjust(str1, length, str2):
    if len(str1)>=length:
        print(str1)
    else:
        for i in range(length-len(str1)):
            print(str2, end='')
        print(str1)

rjust('abc', 7, '0')

13. 寫一個(gè)自己的index函數(shù),統(tǒng)計(jì)指定列表中指定元素的所有下標(biāo),如果列表中沒有指定元素返回 - 1

例如:
列表: [1, 2, 45, 'abc', 1, '你好', 1, 0]
元素: 1
結(jié)果: 0, 4, 6
列表: ['趙云', '郭嘉', '諸葛亮', '曹操', '趙云', '孫權(quán)']
元素: '趙云'
結(jié)果: 0, 4
列表: ['趙云', '郭嘉', '諸葛亮', '曹操', '趙云', '孫權(quán)']
元素: '關(guān)羽'
結(jié)果: -1

def index(list1, elem):
    if elem in list1:
        for i in range(len(list1)):
            if list1[i] == elem:
                print(i, end=',')
                continue
    else:
        print(-1)

index([1, 2, 45, 'abc', 1, '你好', 1, 0], 1)

14. 寫一個(gè)自己的len函數(shù),統(tǒng)計(jì)指定序列中元素的個(gè)數(shù)

例如:
序列:[1, 3, 5, 6]
結(jié)果: 4
序列: (1, 34, 'a', 45, 'bbb')
結(jié)果: 5
序列: 'hello w'
結(jié)果: 7

print()
def len(sequence):
    count = 0
    for i in sequence:
        count += 1
    print("有%d個(gè)元素" % count)

len([1, 3, 5, 6])
len((1, 34, 'a', 45, 'bbb'))
len('hello w')

15. 寫一個(gè)自己的max函數(shù),獲取指定序列中元素的最大值。如果序列是字典,取字典值的最大值

例如:
序列:[-7, -12, -1, -9]
結(jié)果: -1
序列: 'abcdpzasdz'
結(jié)果: 'z'
序列: {'小明': 90, '張三': 76, '路飛': 30, '小花': 98}
結(jié)果: 98

# def my_max(sequence):
#     max_value = 0
#     if type(sequence) == list:
#         for i in range(len(sequence)):
#             for j in range(i+1, len(sequence)):
#                 if sequence[i] >= sequence[j]:
#                     max_value = sequence[i]
#         print(max_value)
#     if type(sequence) == str:
#         for i in sequence:
#             if ord(i) >= max_value:
#                 max_value = ord(i)
#         print(chr(max_value))
#     if type(sequence) == dict:          #需完善
#         for key in sequence:
#             if sequence[key]>=max_value:
#                 max_value = sequence[key]
#         print(max_value)

# my_max([-7, -12, -1, -9])
# my_max('abcdpzasdz')
# my_max({'小明': 90, '張三': 76, '路飛': 30, '小花': 98})
def yt_max(seq):
    if isinstance(seq, dict):
        list1 = list(seq.values())
    else:
        list1 = list(seq)

    max1 = list1[0]
    for index in range(1, len(list1)):
        item = list1[index]
        if item > max1:
            max1 = item

    return max1


print(yt_max([1, 34, 5]))
print(yt_max(['abs', 'shd', 'wf']))
print(yt_max({'a': 100, 'b': 20, 'c': 105}))

16. 寫一個(gè)函數(shù)實(shí)現(xiàn)自己in操作,判斷指定序列中,指定的元素是否存在

例如:
序列: (12, 90, 'abc')
元素: '90'
結(jié)果: False
序列: [12, 90, 'abc']
元素: 90
結(jié)果: True

def if_in(list1, elem):
    for i in list1:
        if elem == i:
            print(True)
        else:
            print(False)

17. 寫一個(gè)自己的replace函數(shù),將指定字符串中指定的舊字符串轉(zhuǎn)換成指定的新字符串

例如: 原字符串: 'how are you? and you?'
舊字符串: 'you'
新字符串: 'me'
結(jié)果: 'how are me? and me?'

#方法一
def yt_replace(str1: str, old: str, new: str):
    return new.join(str1.split(old))


result = yt_replace('aa yoo how are you? and you?', 'you', 'me')
print(result)
#方法二
def yt_replace(str1: str, old: str, new: str):
    strs = []
    temp = ''
    len_old = len(old)
    index = 0
    while index < len(str1):
        char = str1[index]
        if char != old[0]:
            temp += char
        else:
            temp2 = str1[index: index+len_old]
            if temp2 == old:
                strs.append(temp+new)
                temp = ''
                index += len_old
                continue
            else:
                temp += char

        index += 1

    strs.append(temp)

    return ''.join(strs)


print(yt_replace('aa yoo how are you? and you?', 'you', 'me'))
print('aa yoo how are you? and you?'.split('you'))

18. 寫四個(gè)函數(shù),分別實(shí)現(xiàn)求兩個(gè)列表的交集、并集、差集、補(bǔ)集的功能

def inter_set(list1, list2):
    list3 = []
    for i in list1:
        if i in list2:
            list3.append(i)
    print(set(list3))
def union_set(list1, list2):
    list3 = []
    for i in list1:
        list3.append(i)
    for j in list2:
        list3.append(j)
    print(set(list3))
def sub_set(list1, list2):
    list3 = []
    for i in list1:
        if i not in list2:
            list3.append(i)
    print(set(list3))
def comple_set(list1, list2):
    for i in list1:
        if i in list2:
            continue
        else:
            print(list1,"不在",list2,"中")
    else:
        print(list1, "在", list2, "中的補(bǔ)集是:",end='')
        for i in list1:
            list2.remove(i)
        print(list2)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容