zoukankan      html  css  js  c++  java
  • 小圆圈第三章答案

    小圆圈第三章练习题

    • 1.写函数,计算传入数字参数的和。(动态传参)

      def sum_count(*args):
          return sum(args)
      v = sum_count(1, 2, 3, 4)  # 传参数
      print(v)
      
      
    • 2.写函数,用户传入修改的文件名,与要修改的内容,执行函数,完成整个文件的批量修改操作

      import os
      def func():
        usee_path = input('请输入要修改的文件名:')
          if not os.path.exists(usee_path+'.txt'):
              print('输入的文件不存在')
          usee = input('要修改的内容:')
          usee_s = input('内容修改为 :')
          with open(usee_path+'.txt',mode='r',encoding='utf-8') as f:
              for i in f :
                  print(i.strip().replace(usee,usee_s))
      func()
      
      
    • 3.写函数,检查用户传入的对象(字符串、列表、元组)的每一个元素是否含有空内容。

      def func(*args):
          if not all(args):
              return '有空内容'
          return '没有空内容'
      v = func(1,2,3,0)
      print(v)
      
      
    • 4.写函数,检查传入字典的每一个value的长度,如果大于2,那么仅保留前两个长度的内容(对value的值进行截断), 并将新内容返回给调用者,注意传入的数据可以是字符、list、dict

      dic = {'k1':'alex','k2':'aaaaaaaaaaaaaaa','k3':'sb'}
      def func(a):
          for k,v in a.items():
              if not len(v) == 2:
                  a[k]=v[ : 2]
          return a
      v = func(dic)
      print(v)
      
      
    • 5.解释闭包的概念

      def func(arg):
        def info():
        return arg
      return info
      
      v = func('alex')
      v1 = v()
      print(v1)
      
      
    • 6.写函数,返回一个扑克牌列表,里面有52项,每一项是一个元组 例如:[(‘红心’,2),(‘草花’,2), …(‘黑桃A’)]

      lst = [ i for i in range(2,11)]
      lis = ['J','Q','K','A']
      data = lst + lis
      info = ['红心','黑桃','梅花','红方']
      v =[]
      for line in info:
          for i in data:
              i = tuple((line,i))
              v.append(i)
      
      print(v)
      
      
    • 7.写函数,传入n个数,返回字典{‘max’:最大值,’min’:最小值}

      def func(*args):
          count = max(args)
          count_min = min(args)
          return {'max':count,'min':count_min}
      
      
      v = func(1,2,3,4,33,4,4,5,5566,)
      print(v)
      
      
    • 8,8. 写函数,专门计算图形的面积

      其中嵌套函数,计算圆的面积,正方形的面积和长方形的面积

      调用函数area(‘圆形’,圆半径) 返回圆的面积

      调用函数area(‘正方形’,边长) 返回正方形的面积

      调用函数area(‘长方形’,长,宽) 返回长方形的面积

      def area(a1,a2,a3=0):
          '''
          计算 图形面积
          :param a1: 圆形
          :param a2: 半径/长
          :param a3:宽
          :return:
          '''
          def circular():
              print('圆的面积: %s'%(3.14*a2*a2,))
      
          def Square():
              print('正方形的面积:%d'%(a2*a2,))
      
          def Rectangle():
              print('长方形的面积 %d'%(a3*a2,))
      
      # 判断瀛湖输入的图形以调用
          if a1 =='圆形':
              circular()
          elif a1 =='正方形':
              Square()
          else:
              Rectangle()
      
      # 用户输入
      usee_Graphical = input('请输入要计算的图形 :')
      if   usee_Graphical == '圆形':
          usee_radius = int(input('圆的半径:'))
          area(usee_Graphical,usee_radius)
      
      elif  usee_Graphical == '正方形':
          usee_wide = int(input('正方形的边长:'))
          area(usee_Graphical,usee_wide)
      
      elif usee_Graphical=='长方形':
          usee_long = int(input('长方形的长:'))
          usee_long_wode = int(input('长方形的宽 :'))
          area(usee_Graphical,usee_long,usee_long_wode)
      
      
      
    • 9 .写函数,传入一个参数n,返回n的阶乘

      def info (arg):
          sum =1
          for i in range(1,arg):
              sum *=i
          return sum
      
      v = info(7)
      print(v)
      
      
    • 10 编写装饰器,为多个函数加上认证的功能(用户的账号密码来源于文件),要求登录成功一次,后续的函数都无需再输入用户名和密码

      dic = {'账号': 'alex', '密码': 123, '登陆': False}
      def func(arg):
          def info():         
              if dic['登陆'] == True:
                  print('已经登录')
                  arg()
              usee = input('请输入账号:')
              usee_s = int(input('请输入密码:'))
              if usee == dic['账号'] and usee_s == dic["密码"]:
                  print('登陆成功')
                  dic['登陆']=True
                  arg()
              else:
                  print('账号或密码错误')
          return info
      
      @func
      def inner():
          print('____欢迎来到_____')
      
      @func
      def data():
          print('alexnb')
      
      inner()
      data()
      
      
    • 11.用map来处理字符串列表,把列表中所有人都变成sb,比方alex_sb

      name=['alex','wupeiqi','yuanhao','nezha']
      v = map(lambda x :x+'_sb',name)
      for i in v:
          print(i)
      
      
    • 12.用filter函数处理数字列表,将列表中所有的偶数筛选出来

      age = [1,2,34,4,5,66,]
      
      v = filter(lambda x :x%2==0,age)
      for i in v:
          print(i)
      
      
    • 13.如下,每个小字典的name对应股票名字,shares对应多少股,price对应股票的价格

    • 通过哪个内置函数可以计算购买每支股票的总价

    • 用filter过滤出,单价大于100的股票有哪些

    portfolio = [
        {'name': 'IBM', 'shares': 100, 'price': 91.1},
        {'name': 'AAPL', 'shares': 50, 'price': 543.22},
        {'name': 'FB', 'shares': 200, 'price': 21.09},
        {'name': 'HPQ', 'shares': 35, 'price': 31.75},
        {'name': 'YHOO', 'shares': 45, 'price': 16.35},
        {'name': 'ACME', 'shares': 75, 'price': 115.65}
    ]
    data = map(lambda x:x['shares']*x['price'],portfolio)
    for i in data:
        print(i)
    
    
    v = filter(lambda x :x['price']>100,portfolio)
    for i in v:
        print(i)
    
    
    • 14.有列表 li = [‘alex’, ‘egon’, ‘smith’, ‘pizza’, ‘alen’], 请将以字母“a”开头的元素的首字母改为大写字母;

      li = ['name','egon','smith','pizza','aken']
      lst = [i.capitalize() for i in li]
      print(lst)
      
      
    • 有名为poetry.txt的文件,其内容如下,请删除第三行; 昔人已乘黄鹤去,此地空余黄鹤楼。 黄鹤一去不复返,白云千载空悠悠。 晴川历历汉阳树,芳草萋萋鹦鹉洲。 日暮乡关何处是?烟波江上使人愁。

      with open('a.txt',mode='r',encoding='utf-8')as f,open('b.txt',mode='w',encoding='utf-8')as f1:
          data= [ i for i in f]
          data.pop(2)
          for i in data:
              f1.write(i)
      
      
    • 有名为username.txt的文件,其内容格式如下,写一个程序,判断该文件中是否存在”Alex”, 如果没有,则将字符串”Alex”添加到该文件末尾,否则提示用户该用户已存在;

      def func():
          with open('a.txt',mode='r+',encoding='utf-8')as f:
              for i in f:
                  if 'alex' in i.strip():
                      return '存在'
              f.write('
      alex')
              return '以写入'
      
      
      v = func()
      print(v)
      
      
    • 有名为user_info.txt的文件,其内容格式如下,写一个程序,删除id为100003的行

      • pizza,100001
        alex, 100002
        egon, 100003
        
        
        import os
        with open('a.txt',mode='r',encoding='utf-8')as f,open('a1.txt',mode='w',encoding='utf-8')as f1:
            for i in f :
                if '100003' in i:
                    continue
                else:
                    f1.write(i)
        os.remove('a.txt')
        os.rename('a1.txt','a.txt')
        
        
      • 有名为user_info.txt的文件,其内容格式如下,写一个程序,将id为100002的用户名修改为alex li

        import os
        with open('a.txt',mode='r',encoding='utf-8')as f,open('a1.txt',mode='w',encoding='utf-8')as f1:
            for i in f:
                if '100002' in  i:
                    i = i.split(',')
                    i[0]= 'alex li'
                    for line in i:
                        f1.write(line)
                else:
                    f1.write(i)
        os.remove('a.txt')
        os.rename('a1.txt','a.txt')
        
        
      • 写一个计算每个程序执行时间的装饰器;

        import time
        def func(arg):
            def info():
                count_time = time.time()
                arg()
                count_time_s = time.time()
                return float(count_time_s) -float(count_time)
            return info
        
        
        @func
        def inner():
            print('hahaha
        ')
            print('hahaha
        ')
        # print('hahaha
        ')  多打印几行 (50) 不然时间0.0
        print(inner())
        
        
      • lambda是什么?请说说你曾在什么场景下使用lambda?

        lambda 是匿名函数
        def func(a):
        	return a*2
        func(4)
        
        a = lambda x:x*2
        print(a)
        
        
      • 题目:写一个摇骰子游戏,要求用户压大小,赔率一赔一。要求:三个骰子,每个骰子的值从1-6,摇大小,每次打印摇出来3个骰子的值。

        # 题目:写一个摇骰子游戏,要求用户压大小,赔率一赔一。要求:三个骰子,每个骰子的值从1-6,摇大小,每次打印摇出来3个骰子的值。
        import random
        print('----欢迎来到摇骰子游戏-----')
        money = int(input('请输入你的本金:'))
        while 1:
            lst = [random.randint(1,7)  for i in range(3)]
            s = sum(lst)
            usee = int(input('请输入(1 押大,2 押小 0 退出):'))
            if usee =='0':
                break
            usee_money = int(input('你要押多少:'))
            if usee >=3:
                print('输入有误')
            elif usee ==1 and s <20 :
                print('押大了')
                money -=usee_money
                print('你的本金还剩%d'%money)
            elif usee == 2 and s>20:
                print('押大了')
                money -= usee_money
                print('你的本金还剩%d' % money)
            else:
                print('恭喜你押对了')
                money += usee_money
                print('你的本金还剩%d' % money)
            print('本次是%s'%s)
        
        
  • 相关阅读:
    IOC
    paxos算法
    搜索引擎相关
    java常识
    Redis相关概念
    Keepalived简单理解
    LVS简单理解
    dbproxy
    用不上索引的sql
    二叉树、B树、B+树、B*树、VAL树、红黑树
  • 原文地址:https://www.cnblogs.com/xuanxuan360/p/11383224.html
Copyright © 2011-2022 走看看