美文网首页
python函数基础练习

python函数基础练习

作者: fossumjonas | 来源:发表于2019-06-17 09:26 被阅读0次
  1. 编写函数,求1+2+3+…N的和
def sum1(n):
    sum2 = 0
    for i in range(1, n+1):
        sum2 += i
    return sum2
print(sum1(5))
  1. 编写一个函数,实现摇骰子的功能,打印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
    return  sum_roll

print(roll(3))

  1. 编写一个函数,交换指定字典的key和value。
# 例如:dict1={'a':1, 'b':2, 'c':3}  -->  dict1={1:'a', 2:'b', 3:'c'}  
def change_dict(dict1):
    new_dict = {}  
    for key in dict1:
        new_dict[dict1[key]] = key  
    print(new_dict)
    
change_dict(a=1, b=2, c=3)  # {1: 'a', 2: 'b', 3: 'c'}



def change_dict(dict1):
    for key in dict1.copy():
        value = dict1.pop(key)
        dict1[value] = key 
dict1={'a':1, 'b':2, 'c':3}
change_dict(dict1)
print(dict1)
  
  1. 编写一个函数,提取指定字符串中所有的字母,然后拼接在一起产生一个新的字符串
# 例如: 传入'12a&bc12d-+'   -->  'abcd'  

def string_s(str1):
    str2 = ''
    for item in str1[:]:
        if 'A' <= item <= 'Z' or 'a' <= item <= 'z':
            str2 += item
    return str2

string_s('12a&bc12d-+')   
  1. 写一个函数,求多个数的平均值

def avg(*n):
    print(sum(n)/len(n))
avg(1, 5, 5, 8)

  1. 写一个函数,默认求10的阶乘,也可以求其他数字的阶乘
def jiecheng(n):
    result1 = 1
    for i in range(1, n+1):
        result1 *= i
    print(result1)

jiecheng(10)

=====================注意:以下方法不能使用系统提供的方法和函数,全部自己写逻辑==============
  1. 写一个自己的capitalize函数,能够将指定字符串的首字母变成大写字母
# 例如: 'abc' -> 'Abc'   '12asd'  --> '12asd'
def capitaliza_ex(str1):
    item = str1[0]
    str2 = ''
    if 'a' <= item <= 'z':
        new_item = chr((ord(item)) - 32)
        str2 = new_item + str1[1:]
        print(str2)
    else:
        print('首字母不是小写')

capitaliza_ex('a1asdsa')

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

def endswith_e(str1, end):
    length = len(end)
    if str1[-length, -1] == end :
        return True
    return False


print(endswith_e('acvcv', 'cv'))
  1. 写一个自己的isdigit函数,判断一个字符串是否是纯数字字符串
# 例如: '1234921'  结果: True
# '23函数'   结果: False
#  'a2390'    结果: False
def n_isdigit(str1):
    num = 0
    for i in str1:
        if  not '0' <= i <= '9':
            num += 1
    if num == 0:
        print('True')
    else:
        print('False')

n_isdigit('12l3456')
         
  1. 写一个自己的upper函数,将一个字符串中所有的小写字母变成大写字母
# 例如: 'abH23好rp1'   结果: 'ABH23好RP1'  
def upper_a(str1):
    str2 = ''
    for item in str1:
        if  'a' <= item <= 'z':
            new_item = chr((ord(item)) - 32)
            str2 += new_item
        else:
            str2 += item
    print(str2)
upper_a('asnnAA55')
    
    
  1. 写一个自己的rjust函数,创建一个字符串的长度是指定长度,原字符串在新字符串中右对齐,剩下的部分用指定的字符填充
# 例如: 原字符:'abc'  宽度: 7  字符:'^'    结果: '^^^^abc'
# 原字符:'你好吗'  宽度: 5  字符:'0'    结果: '00你好吗'

def rjust_func(str1:str,length:int,str2:str):
    new_str = ''
    new_str = str2 * (length-len(str1)) + str1
    return new_str


a = rjust_func('abc',7,'^')
print(a)   

  1. 写一个自己的index函数,统计指定列表中指定元素的所有下标,如果列表中没有指定元素返回-1
# 例如: 列表: [1, 2, 45, 'abc', 1, '你好', 1, 0]  元素: 1   结果: 0,4,6  
  #       列表: ['赵云', '郭嘉', '诸葛亮', '曹操', '赵云', '孙权']  元素: '赵云'   结果: 0,4
 #
  #      列表: ['赵云', '郭嘉', '诸葛亮', '曹操', '赵云', '孙权']  元素: '关羽'   结果: -1         
def index_func(list1:list,str2):  
    if str2 in list1:
        for index in range(len(list1)):
            if str2 == list1[index]:
                print(index,end=(','))
        print()
    else:
        print('-1')


index_func([1, 2, 45, 'abc', 1, '你好', 1, 0],1)   # 0,4,6,
index_func(['赵云', '郭嘉', '诸葛亮', '曹操', '赵云', '孙权'],'赵云')  # 0,4
index_func(['赵云', '郭嘉', '诸葛亮', '曹操', '赵云', '孙权'],'关羽')  # -1


  1. 写一个自己的len函数,统计指定序列中元素的个数
# 例如: 序列:[1, 3, 5, 6]    结果: 4
# 序列:(1, 34, 'a', 45, 'bbb')  结果: 5  
# 序列:'hello w'    结果: 7
def  def_func(a):
    count = 0
    for item in a:
        count += 1
    print(count)

def_func([1, 3, 5, 6])

  1. 写一个自己的max函数,获取指定序列中元素的最大值。如果序列是字典,取字典值的最大值
#    例如: 序列:[-7, -12, -1, -9]    结果: -1   
#         序列:'abcdpzasdz'    结果: 'z'  
#         序列:{'小明':90, '张三': 76, '路飞':30, '小花': 98}   结果: 98
def max_seq(a):
    list1 = list(a)
    if type(a) == dict:
        list1 = list(a.values())
    max1 = list1[0]
    for item in list1[1:]:
        if max1 < item:
            max1 = item
    return max1
 
print(max_seq({'小明':90, '张三': 76, '路飞':30, '小花': 98}  )) # 98
print(max_seq("abcdpzasdz"  ) )# z
print(max_seq([-7, -12, -1, -9]))  # -1

        
         


  1. 写一个函数实现自己in操作,判断指定序列中,指定的元素是否存在
# 例如: 序列: (12, 90, 'abc')   元素: '90'     结果: False
# 序列: [12, 90, 'abc']   元素: 90     结果: True   
         
         
def in_func(a,b):
    for item in a:
        if item == b:
            print('Ture')
            break
    else:
        print('False')
in_func([12, 90, 'abc'], 90) 
  1. 写一个自己的replace函数,将指定字符串中指定的旧字符串转换成指定的新字符串

# 例如: 原字符串: 'how are you? and you?'   旧字符串: 'you'  新字符串:'me'  结果: 'how are me? and me?'
def rep_str(str1 :str, str2 : str,  str3 : str, ):
    str4 = ""
    index = 0
    while index < len(str1):    # str1 指定的待旧换新字符串
        if str1[index : (index + len(str2) )] == str2:    # str2旧的字符串
            str4 += str3  # str3指定的新字符串
            index += len(str2)
        else:
            str4 += str1[index]
            index += 1
 
    return str4
 
print(rep_str( 'how are you? and you?',  'you', "me" )) # how are me? and me?



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

def jiao_func(list1:list,list2:list):
    for i in list1:
        if i in list2:
            print(i,end=',')
    print()

jiao_func([1,2,3,4],[1,2,3,4,5,6,7,8,9])   # 1,2,3,4,



def bing_func(list1:list,list2:list):
    for i in list1:
        if i not in list2:
            list2.append(i)
    return list2


a = bing_func([1,2,3,4,10],[1,2,3,4,5,6,7,8,9])
print(a)   # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]



def cha_func(list1:list,list2:list):
    new_list = []
    for i in list1:
        if i not in list2:
            new_list.append(i)
    return new_list


a = cha_func([1,2,3,4,10],[1,2,3,4,5,6,7,8,9])  # [10]
print(a)



def bu_func(list1:list,list2:list):
    new_list = []
    for index1 in list1:
        if index1 not in list2:
            new_list.append(index1)
    for index2 in list2:
        if index2 not in list1:
            new_list.append(index2)
    return new_list


a = bu_func([1,2,3,4,10],[1,2,3,4,5,6,7,8,9])   # [10, 5, 6, 7, 8, 9]
print(a)

相关文章

  • Python基础练习:函数练习

    练习点:创建函数,参数收集,嵌套函数,装饰器 1、创建函数 编写函数,对单词中的字母实现下列操作: -----根据...

  • python函数基础练习

    编写函数,求1+2+3+…N的和 编写一个函数,实现摇骰子的功能,打印N个骰子的点数和 编写一个函数,交换指定字典...

  • 推荐一个python练习网站:随时可测试自己的能力

    推荐一个python练习网站w3resource,练习题包括python的基础数据类型,函数、内置的一些库比如os...

  • 一个很香的python练习网站

    推荐一个python练习网站w3resource,练习题包括python的基础数据类型,函数、内置的一些库比如os...

  • python基础笔记

    Python基础 函数:

  • python练习(2)

    python学习的第二周,这周学习继续学习python基础,主要是生成器、函数式编程、模块。部分练习如下: 下周将...

  • Python入门

    Python3教程 安装Python 第一个Python程序 Python基础 函数 高级特性 函数式编程 模块 ...

  • Python | 词频统计

    最近工作蛮忙的,就简单练习一下python基础吧。 本周的练习是词频统计,主要使用了以下几个函数: text.sp...

  • 3-Python 函数(2)

    本章概要:1、函数基础2、深入理解函数3、综合练习 1、函数基础 课程概要:理解函数定义函数调用函数函数文档 一、...

  • python入门套路

    Python基础 基础数据类型 bool string list tuple dictionary 基础函数 he...

网友评论

      本文标题:python函数基础练习

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