day09-作业

1.编写一个函数,求1+2+3+...+N

def my_sum(n:int):
    sum = 0
    for i in range(1,n+1):
        sum += i
    return sum

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

def find_max(*args):
    return max(args)

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

import random
def shake(n:int):
    sum = 0
    for i in range(n):
        # 随机生成1-6的整数,模拟摇色子
        sum += random.randint(1,6)
    print("%d个色子的点数和为:%d" % (n,sum))

4.编写一个函数,交换指定字典的key和value。

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

def change_dict(dict1:dict):
    for index in dict1:
        t_key = dict[index]
        t_value = index
        del dict1[index]
        dict1[t_key] = t_value

dict = {'a':1, 'b':2, 'c':3}
change_dict(dict)
print(dict)

5.编写一个函数,三个数中的最大值

def my_max(a,b,c):
    return max((a,b,c))

print(my_max(1,2,3))

6.编写一个函数,提取指定字符串中的所有的字母,然后拼接在一起后打印出来

例如:'12a&bc12d--' ---> 打印'abcd'

def print_letters(s):
    list_str = list(s)
    for item in list_str[:]:
        if not ('A'<=item<='Z' or 'a'<=item <='z'):
            list_str.remove(item)
    return ''.join(list_str) 

str = '12a&bc12d--'
print(print_letters(str))

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

def my_average(*args):
    sum = 0
    for item in args:
        sum += item
    return sum / len(args)

print(my_average(1,2,3,4,5,6,7))

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

def factorial(n = 10):
    fact = 1
    for item in range(1,n+1):
        fact *= item
    print("%d的阶乘为:%d" % (n,fact))
    return fact

factorial()
factorial(5)

9.写一个函数,可以对多个数进行不同的运算

例如: operation('+', 1, 2, 3) ---> 求 1+2+3的结果
operation('-', 10, 9) ---> 求 10-9的结果
operation('*', 2, 4, 8, 10) ---> 求 2*4*8*10的结果
def operation(oper,*num):
    if oper == '+':
        sum = 0
        for item in num:
            sum += item
        return sum
    elif oper == '-':
        sum = num[0] 
        for item in num[1:]:
            sum -= item
        return sum
    elif oper == '*':
        product = 1
        for item in num:
            product *= item
        return product
    elif oper == '/':
        product = num[0]
        for item in num[1:]:
            product /= item
        return product
    else:
        print('输入运算符有误')
        return 0

print(operation('+', 1, 2, 3))  # 6 = 1+2+3
print(operation('-', 1, 2, 3))  # -4 = 1-2-3
print(operation('*', 1, 2, 3))  # 6 = 1*2*3
print(operation('/', 1, 2, 3))  # 0.16666666666666666 = 1/2/3
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • import random 1. 编写一个函数,求1+2+3+...+N 2. 编写一个函数,求多个数中的最大值 ...
    Heyjoky阅读 1,373评论 0 0
  • 1. 编写一个函数,求1+2+3+...+N 2.编写一个函数,求多个数中的最大值 3. 编写一个函数,实现摇骰...
    PythonLi阅读 2,767评论 0 0
  • 8月22日-----字符串相关 2-3 个性化消息: 将用户的姓名存到一个变量中,并向该用户显示一条消息。显示的消...
    future_d180阅读 4,553评论 0 1
  • 1、写一个函数将一个指定的列表中的元素逆序(例如,[1,2,3]->[3,2,1])注意:不要使用列表自带的逆序函...
    d4lx阅读 1,517评论 0 0
  • 1.写一个匿名函数,判断指定的年是否是闰年 2.写一个函数将一个指定的列表中的元素逆序( 如[1, 2, 3] -...
    barriers阅读 1,459评论 0 0

友情链接更多精彩内容