01.04 作业

  1. 编写一个函数,求1+2+3+...+N
def sum(N):
    sum = 0
    for i in range(1, N + 1):
        sum += i
    print(sum)

sum(5)
  1. 编写一个函数,求多个数中的最大值
def maxItem(*args):
    print(max(args))

maxItem(1, 2, 3, 4, 5)
  1. 编写一个函数,实现摇色子的功能,打印n个色子的点数和
def dialectN(N):
    import random
    sum = 0
    for i in range(1, N + 1):
        dialect = random.randrange(1, 7)
        sum += dialect
    print(sum)

dialectN(5)

  1. 编写一个函数,交换指定字典的key和value。
    例如:{'a':1, 'b':2, 'c':3} ---> {1:'a', 2:'b', 3:'c'}
def changeKeyAndValue(olddict):
    newdict = dict(zip(olddict.values(), olddict.keys()))
    print(newdict)

changeKeyAndValue({'a': 1, 'b':2})

  1. 编写一个函数,三个数中的最大值
def maxThree(*value):
    print(max(value))

maxThree(1,2,3)

  1. 编写一个函数,提取指定字符串中的所有的字母,然后拼接在一起后打印出来。例如:'12a&bc12d--' ---> 打印'abcd'
def strWords(oldstr):
    newstr = ''.join([ i for i in oldstr if i.isalpha()])
    print(newstr)

strWords('12a&bc12d')

  1. 写一个函数,求多个数的平均值
def avrg(*values):
    print(sum(values) / len(values))

avrg(2,5,1,3,4)

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

jiecheng()

  1. 写一个函数,可以对多个数进行行不同的运算。例如: operation('+', 1, 2, 3) ---> 求 1+2+3的结果 operation('-', 10, 9) ---> 求 10-9的结果 operation('*', 2, 4, 8, 10) ---> 求 2*4*8*10的结构
def multiOperation(opre, *values):
    new_str = opre.join([str(i) for i in values])
    print(eval(new_str))

multiOperation('+', 1,2,3)

你可能感兴趣的:(01.04 作业)