DAY10作业-函数

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

def m_sum(n):
   sum1 = 0
   for items in range(n+1):
       sum1 = sum1 + items
   return sum1


print(m_sum(100))

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

def m_max(*nums):
    max1 = nums[0]
    for items in nums:
        if items > max1:
            max1 = items
    return max1


print(m_max(1, 2, 3, 4, 5))

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

import random


def dice(n):
    sum1 = 0
    num_list = []
    while n > 0:
        num_list.append(random.randint(1, 6))
        n = n - 1
    return sum(num_list)


n = int(input("要摇几次骰子?"))
print("总和是:%d" % dice(n))
  1. 编写一个函数,交换指定字典的key和value。
    例如:dict1={'a':1, 'b':2, 'c':3} --> dict1={1:'a', 2:'b', 3:'c'}
def change_dict(dic):
    for key in dic:
        new_key = dic[key]
        new_value = key
        dic.pop(key)
        dic[new_key] = new_value
    return dic


dict1 = {'a': 1, 'b': 2, 'c': 3}
print(change_dict(dict1))
  1. 编写一个函数,提取指定字符串中所有的字母,然后拼接在一起产生一个新的字符串
    例如: 传入'12a&bc12d-+' --> 'abcd'
def extract_letters(str1):
    new_str = ''
    for items in str1:
        if 'a' <= items <= 'z' or 'A' <= items <= 'Z':
            new_str += items
    return new_str


str1 = input('输入字符串')
print("提取字母:%s" % extract_letters(str1))

6.写一个函数,求多个数的平均值

def ave(nums):
    aver = sum(nums) / len(nums)
    return aver


num_list = []
num_str = input("输入一串数字,空格隔开:")
new_str = []
new_str = num_str.split(' ')
for items in new_str:
    num_list.append(int(items))
print("平均值是:%.2f" % ave(num_list))

7.写一个函数,默认求10的阶乘,也可以求其他数字的阶乘

def factorial(n=10):
    fac = 1
    for num in range(1, n+1):
        fac = num * fac
    return fac


n = int(input('输入一个数:'))
print("该数的阶乘是:%d" % factorial(n))
  1. 写一个自己的capitalize函数,能够将指定字符串的首字母变成大写字母
    例如: 'abc' -> 'Abc' '12asd' --> '12asd'
def m_capitalize(str1):
    new_str = ''
    if 'a' <= str1[0] <= 'z':
        new_str += chr(ord(str1[0])-32)
    for index in range(1, len(str1)):
        new_str += str1[index]
    return new_str


str2 = input("输入一串字符")
print("修改后:%s" % m_capitalize(str2))

9.写一个自己的endswith函数,判断一个字符串是否已指定的字符串结束
例如: 字符串1:'abc231ab' 字符串2:'ab' 函数结果为: True
字符串1:'abc231ab' 字符串2:'ab1' 函数结果为: False

str1 = input("输入判断的字符串:")
str2 = input("结束的标志是:")


def m_endswith(judge_str, ends_str):
    flag = 1
    index2 = 0
    for index in range(len(judge_str)-len(ends_str),len(judge_str)):
        if judge_str[index] != ends_str[index2]:
            flag = 0
        index2 += 1
    if flag == 1:
        return True
    else:
        return False


print("函数结果是%s" % m_endswith(str1, str2))
  1. 写一个自己的isdigit函数,判断一个字符串是否是纯数字字符串
    例如: '1234921' 结果: True
    '23函数' 结果: False
    'a2390' 结果: False
num_str = input("输入字符串:")


def m_isdigit(nums_str):
    flag = 1
    for num in nums_str:
        if not('0' <= num <= '9'):
            flag = 0
    if flag == 1:
        return True
    else:
        return False


print("结果是%s" % m_isdigit(num_str))
  1. 写一个自己的upper函数,将一个字符串中所有的小写字母变成大写字母
    例如: 'abH23好rp1' 结果: 'ABH23好RP1'
str1 = input("输入字符串:")


def m_upper(last_str):
    new_str = ''
    for char in last_str:
        if 'a' <= char <= 'z':
            new_str += chr(ord(char)-32)
        else:
            new_str += char
    return new_str


print("新字符串是:%s" % m_upper(str1))
  1. 写一个自己的rjust函数,创建一个字符串的长度是指定长度,原字符串在新字符串中右对齐,剩下的部分用指定的字符填充
    例如: 原字符:'abc' 宽度: 7 字符:'^' 结果: '^^^^abc'
    原字符:'你好吗' 宽度: 5 字符:'0' 结果: '00你好吗'
str1 = input("输入字符串:")
width = int(input("输入宽度:"))
fill_char = input("输入补充字符:")


def m_rjust(last_str, user_width, user_fillchar):
    new_str = ''
    if len(last_str) < user_width:
        for count in range(width - len(last_str)):
            new_str += user_fillchar
        new_str += last_str
    return  new_str


print("新字符串是:%s" % m_rjust(str1,width,fill_char))

13.写一个自己的index函数,统计指定列表中指定元素的所有下标,如果列表中没有指定元素返回-1
例如: 列表: [1, 2, 45, 'abc', 1, '你好', 1, 0] 元素: 1 结果: 0,4,6
列表: ['赵云', '郭嘉', '诸葛亮', '曹操', '赵云', '孙权'] 元素: '赵云' 结果: 0,4
列表: ['赵云', '郭嘉', '诸葛亮', '曹操', '赵云', '孙权'] 元素: '关羽' 结果: -1

list_str = input("输入列表,逗号隔开:")
list1 = list_str.split(',')
index1 = input("指定元素:")


def m_index(user_list, user_index):
    index_str = ''
    flag = 0
    for index in range(len(user_list)):
        if user_list[index] == user_index:
            flag = 1
            index_str += str(index)
    if flag == 0:
        index_str += '-1'
    return index_str


print("下标是:%s" % m_index(list1, index1))

14.写一个自己的len函数,统计指定序列中元素的个数
例如: 序列:[1, 3, 5, 6] 结果: 4
序列:(1, 34, 'a', 45, 'bbb') 结果: 5
序列:'hello w' 结果: 7

str1 = (1, 34, 'a', 45, 'bbb')


def m_len(user_str):
    count = 0
    for char in user_str:
        count += 1
    return count


print("结果是:%d" % m_len(str1))

15.写一个自己的max函数,获取指定序列中元素的最大值。如果序列是字典,取字典值的最大值
例如: 序列:[-7, -12, -1, -9] 结果: -1
序列:'abcdpzasdz' 结果: 'z'
序列:{'小明':90, '张三': 76, '路飞':30, '小花': 98} 结果: 98

str1 = {'小明': 90, '张三': 76, '路飞': 30, '小花': 98}


def m_max(user_str):
    if type(user_str) == dict:
        for key in user_str:
            user_max = user_str[key]
        for key in user_str:
            if user_max < user_str[key]:
                user_max = user_str[key]
    else:
        user_max = user_str[0]
        for char in user_str:
            if char > user_max:
                user_max = char
    return user_max


print("最大值是%s" % m_max(str1))

16.写一个函数实现自己in操作,判断指定序列中,指定的元素是否存在
例如: 序列: (12, 90, 'abc') 元素: '90' 结果: False
序列: [12, 90, 'abc'] 元素: 90 结果: True


str1 = [12, 90, 'abc']
judge = 90


def m_in(user_str,user_judge):
    flag = 0
    for char in user_str:
        if char == user_judge:
            flag = 1
    if flag == 0:
        return False
    else:
        return True


print("结果是:%s" % m_in(str1, judge))

17.写一个自己的replace函数,将指定字符串中指定的旧字符串转换成指定的新字符串
例如: 原字符串: 'how are you? and you?' 旧字符串: 'you' 新字符串:'me' 结果: 'how are me? and me?'

str1 = input("输入字符串")
old = input("输入旧字符串")
new = input("输入新字符串")


def m_replace(user_str, user_old, user_new):
    new_str = ''
    index = 0
    while index < len(user_str):
        # 如果开头的字符相同则继续往下判断
        if user_str[index] == user_old[0]:
            flag = 1
            for index_again in range(len(user_old)):
                # 遇到不同的字符 则flag为0
                if user_str[index+index_again] != user_old[index_again]:
                    flag = 0
            # flag为1表示相同,用new替换old 不是就用原字符串替换
            if flag == 1:
                for char in user_new:
                    new_str += char
                index += len(user_old)
            else:
                new_str += user_str[index]
                index += 1
        else:
            new_str += user_str[index]
            index += 1
    return new_str


print("新字符串是:%s" % m_replace(str1, old, new))

18.写四个函数,分别实现求两个列表的交集、并集、差集、补集的功能

list1 = [1, 2, 3, 4]
list2 = [2, 3, 4, 5, 6]


def intersection(list_one, list_two):
    new_list = []
    for items in list_one:
        if items in list_two:
            new_list.append(items)
    return new_list


print("交集是%s" % intersection(list1, list2))


def union(list_one: list, list_two):
    for items in list_two:
        if items not in list_one:
            list_one.append(items)
    list_two = [1, 2, 3]
    return list_one


print("并集是%s" % union(list1, list2), list2)


list1 = [1, 2, 3, 4, 6, 7]
list2 = [2, 3, 4, 5, 6]


def difference(list_one, list_two):
    new_list = []
    for items in list_one:
        if items not in list_two:
            new_list.append(items)
    return new_list


print("差集是%s" % difference(list1, list2))


def symmetric(list_one, list_two):
    new_list = []
    for items in list_one:
        if items not in list_two:
            new_list.append(items)
    for items in list_two:
        if items not in list_one:
            new_list.append(items)
    return new_list


print("补集是%s" % symmetric(list1, list2))
  1. 写一个匿名函数,判断指定的年是否是闰年
leapp = lambda user_year: bool((user_year % 4 == 0 and user_year % 100 != 0) or user_year % 400 == 0)

year = int(input("输入年份"))
print("%d是闰年吗?%s" % (year, leapp(year)))

2.写一个函数将一个指定的列表中的元素逆序( 如[1, 2, 3] -> [3, 2, 1])(注意:不要使用列表自带的逆序函数)

list1 = [1, 2, 3]


def reverse(user_list):
    new_list=[]
    for items in user_list[::-1]:
        new_list.append(items)
    return new_list


print(reverse(list1))

3.写一个函数,获取指定列表中指定元素的下标(如果指定元素有多个,将每个元素的下标都返回)
例如: 列表是:[1, 3, 4, 1] ,元素是1, 返回:0,3

list1 = [1, 3, 4, 1]


def list_index(user_list, num):
    index_list = []
    for index in range(len(user_list)):
        if user_list[index] == num:
            index_list.append(index)
    return index_list


print("下标是:%s" % list_index(list1, 1))

4.写一个函数,能够将一个字典中的键值对添加到另外一个字典中(不使用字典自带的update方法)

dict1 = {'a': 1, 'b': 2, 'c': 3}
dict2 = {'d': 4, 'e':5}


def m_update(dict_one, dict_two):
    for key in dict_two:
        if key not in dict_one:
            dict_one[key] = dict_two[key]
    return dict_one


print(m_update(dict1, dict2))

5.写一个函数,能够将指定字符串中的所有的小写字母转换成大写字母;所有的大写字母转换成小写字母(不能使用字符串相关方法)

str1 = input("输入一串字母:")


def change(user_str):
    new_str = ''
    for items in user_str:
        if 'a' <= items <= 'z':
            new_str += chr(ord(items)-32)
        elif 'A' <= items <= 'Z':
            new_str += chr(ord(items)+32)
        else:
            new_str += items
    return new_str


print("新字符串是:%s" % change(str1))
  1. 实现一个属于自己的items方法,可以将自定的字典转换成列表。
    列表中的元素是小的列表,里面是key和value (不能使用字典的items方法)
    例如:{'a':1, 'b':2} 转换成 [['a', 1], ['b', 2]]
dict1 = {'a': 1, 'b': 2}


def m_itemst(user_dict):
    out_list = []
    for key in user_dict:
        in_list = [key, user_dict[key]]
        out_list.append(in_list)
    return out_list


print(m_items(dict1))

7.写一个函数,实现学生的添加功能:
=============添加学生================
输入学生姓名: 张胜
输入学生年龄: 23
输入学生电话: 15634223
===添加成功!
'姓名':'张胜', '年龄':23, '电话:15634223', '学号':'0001'
=====================================
1.继续
2.返回
请选择: 1
=============添加学生================
输入学生姓名: 李四
输入学生年龄: 18
输入学生电话: 157234423
===添加成功!
'姓名':'张胜', '年龄':23, '电话:15634223', '学号':'0001'
'姓名':'李四', '年龄':18, '电话:157234423', '学号':'0002'
=====================================
1.继续
2.返回
请选择:

number = 1
all_student = []
choose = 1
while choose == 1:
    print("=============添加学生================")
    stu_name = input("输入学生姓名:")
    stu_age = input("输入学生年龄:")
    stu_tel = input("输入学生电话:")
    stu_number = str(number)
    stu_dict = {'姓名': stu_name, '年龄': stu_age, '电话': stu_tel, '学号': stu_number.rjust(3, '0')}
    all_student.append(stu_dict)
    print(all_student)
    print("===添加成功!")
    for stu in all_student:
        print(stu)
    print("=====================================")
    print("1.继续")
    print("2.返回")
    choose = int(input())
    number += 1
   
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,907评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,987评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,298评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,586评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,633评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,488评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,275评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,176评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,619评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,819评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,932评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,655评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,265评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,871评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,994评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,095评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,884评论 2 354

推荐阅读更多精彩内容

  • 概要 64学时 3.5学分 章节安排 电子商务网站概况 HTML5+CSS3 JavaScript Node 电子...
    阿啊阿吖丁阅读 9,197评论 0 3
  • 官网 中文版本 好的网站 Content-type: text/htmlBASH Section: User ...
    不排版阅读 4,381评论 0 5
  • 一、Python简介和环境搭建以及pip的安装 4课时实验课主要内容 【Python简介】: Python 是一个...
    _小老虎_阅读 5,746评论 0 10
  • 1. 编写函数,求1+2+3+…N的和 2. 编写一个函数,求多个数中的最大值 3. 编写一个函数,实现摇骰子的功...
    Dipper_835f阅读 239评论 0 0
  • 编写函数,求1+2+3+…N的和 编写一个函数,求多个数中的最大值 编写一个函数,实现摇骰子的功能,打印N个骰子的...
    胆小的小喷菇阅读 190评论 0 0