美文网首页
day10作业

day10作业

作者: 我去买个橘子o | 来源:发表于2019-03-15 21:02 被阅读0次

1. 编写函数,求1 + 2 + 3 +…N的和

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

print(sum1(6))

2. 编写一个函数,求多个数中的最大值

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

print(max_num(1, 2, 3))

3. 编写一个函数,实现摇骰子的功能,打印N个骰子的点数和

def roll(n):
    import random
    sum_roll = 0
    for i in range(1, n+1):
        num = random.randint(1, 6)
        print("第%d个骰子的点数是:" %i, num)
        sum_roll += num
    print("总的点数是:", sum_roll)

roll(3)

4. 编写一个函数,交换指定字典的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. 编写一个函数,提取指定字符串中所有的字母,然后拼接在一起产生一个新的字符串

例如: 传入 '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. 写一个函数,求多个数的平均值

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. 写一个函数,默认求10的阶乘,也可以求其他数字的阶乘

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

rect(12)


注意:以下方法不能使用系统提供的方法和函数,全部自己写逻辑**

8. 写一个自己的capitalize函数,能够将指定字符串的首字母变成大写字母

例如: '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. 写一个自己的endswith函数,判断一个字符串是否以指定的字符串结束

例如: 字符串1:'abc231ab'
字符串2: 'ab'
函数结果为: True
字符串1: 'abc231ab'
字符串2: 'ab1'
函数结果为: 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. 写一个自己的isdigit函数,判断一个字符串是否是纯数字字符串

例如:
'1234921' 结果: True
'23函数' 结果: False
'a2390' 结果: False

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

isdigital('1235678')

11. 写一个自己的upper函数,将一个字符串中所有的小写字母变成大写字母

例如:
'abH23好rp1' 结果: 'ABH23好RP1'

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

upper('asq24hio')

12.写一个自己的rjust函数,创建一个字符串的长度是指定长度,原字符串在新字符串中右对齐,剩下的部分用指定的字符填充

例如:
原字符:'abc'
宽度: 7
字符: '^'
结果: '^^^^abc'
原字符: '你好吗'
宽度: 5
字符: '0'
结果: '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. 写一个自己的index函数,统计指定列表中指定元素的所有下标,如果列表中没有指定元素返回 - 1

例如:
列表: [1, 2, 45, 'abc', 1, '你好', 1, 0]
元素: 1
结果: 0, 4, 6
列表: ['赵云', '郭嘉', '诸葛亮', '曹操', '赵云', '孙权']
元素: '赵云'
结果: 0, 4
列表: ['赵云', '郭嘉', '诸葛亮', '曹操', '赵云', '孙权']
元素: '关羽'
结果: -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. 写一个自己的len函数,统计指定序列中元素的个数

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

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

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

15. 写一个自己的max函数,获取指定序列中元素的最大值。如果序列是字典,取字典值的最大值

例如:
序列:[-7, -12, -1, -9]
结果: -1
序列: 'abcdpzasdz'
结果: 'z'
序列: {'小明': 90, '张三': 76, '路飞': 30, '小花': 98}
结果: 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. 写一个函数实现自己in操作,判断指定序列中,指定的元素是否存在

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

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

17. 写一个自己的replace函数,将指定字符串中指定的旧字符串转换成指定的新字符串

例如: 原字符串: 'how are you? and you?'
旧字符串: 'you'
新字符串: 'me'
结果: '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. 写四个函数,分别实现求两个列表的交集、并集、差集、补集的功能

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, "中的补集是:",end='')
        for i in list1:
            list2.remove(i)
        print(list2)

相关文章

网友评论

      本文标题:day10作业

      本文链接:https://www.haomeiwen.com/subject/wdcdmqtx.html