2019-01-04作业

2019-01-04  本文已影响0人  白与黑_d83f

import random

  1. 编写一个函数,求1+2+3+...+N
def sum_n(n):
    s = 0
    for i in range(1, n+1):
        s += i
    print(s)
sum_n(10)
  1. 编写一个函数,求多个数中的最大值
def max_muti(*args):
    print(max(args))
max_muti(1, 2, 3, 45, 6, 7)
  1. 编写一个函数,实现摇色子的功能,打印n个色子的点数和
def sum_dice(n : int):
    dice = []
    s = 0
    for i in range(1, n+1):
        dice.append(random.randint(1, 6))
    s += sum(dice)
    print(s)
sum_dice(5)
  1. 编写一个函数,交换指定字典的key和value。
    例如:{'a':1, 'b':2, 'c':3} ---> {1:'a', 2:'b', 3:'c'}
def exchange_key_value(n:dict):
    new_dict = {}
    for key in n:
        new_dict[n[key]] = key
    print(new_dict)
exchange_key_value({'a':1, 'b':2, 'c':3})
  1. 编写一个函数,三个数中的最大值
def max_three_num(a, b, c):
    m = 0
    list1 = []
    list1.append(a)
    list1.append(b)
    list1.append(c)
    m = max(list1)
    print(m)
max_three_num(110, 256, 389)
  1. 编写一个函数,提取指定字符串中的所有的字母,然后拼接在一起后打印出来
    例如:'12a&bc12d--' ---> 打印'abcd'
def alphabet(s: str):
    new_list = []
    for i in (s):
        if 'a' <= i <= 'z' or 'A' <= i <= 'Z':
            print(i, end = '')
  1. 写⼀一个函数,求多个数的平均值
def mean(*args):
    list1 = list(args)
    m = sum(list1) / (len(list1))
    print(m)
mean(5,10,15,100,555)
alphabet('12a&bc12d--')
  1. 写一个函数,默认求10的阶层,也可以求其他数的阶层
def fac(n : int):
    f = 1
    for i in range(1, n+1):
        f *= i
    print(f)
fac(10)
  1. 写⼀一个函数,可以对多个数进行不同的运算
    例例如: operation('+', 1, 2, 3) ---> 求 1+2+3的结果
    operation('-', 10, 9) ---> 求 10-9的结果
    operation('', 2, 4, 8, 10) ---> 求 24810的结构
def operation(operator, *args):
    print(operator, args)
    if operator == '+':
        s = sum(args)
        print(s)
    if operator =='-':
        substraction=0
        for i in args[:]:
            substraction -= i
        subs=substraction+args[0]
        print(subs)
    if operator == '*':
        multi = 1
        for i in (args):
            multi *= i
        print(multi)
operation('-',1,2,3,4,5)
上一篇 下一篇

猜你喜欢

热点阅读