Little Circle Chapter 3 Answers

Little Circle Chapter 3 Exercise Questions

  • 1. Write functions to calculate the sum of the incoming numeric parameters. (dynamic parameter transfer)

    def sum_count(*args):
        return sum(args)
    v = sum_count(1, 2, 3, 4)  # Transfer parameters
    print(v)
    
  • 2. Write the function, the user passes in the modified file name, and the content to be modified, execute the function, and complete the batch modification operation of the whole file.

    import os
    def func():
      usee_path = input('Please enter the name of the file to be modified:')
        if not os.path.exists(usee_path+'.txt'):
            print('Input file does not exist')
        usee = input('Contents to be modified:')
        usee_s = input('The content was amended to read :')
        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. Write functions to check whether each element of the user's incoming object (string, list, tuple) contains empty content.

    def func(*args):
        if not all(args):
            return 'Free content'
        return 'No empty content'
    v = func(1,2,3,0)
    print(v)
    
  • 4. Write a function to check the length of each value passed into the dictionary. If it is greater than 2, only the contents of the first two lengths are retained (truncation of the value).
    Return the new content to the caller, noting that the incoming data can be characters, list s, dict s

    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. Explain the concept of closures

    def func(arg): 
      def info():
      return arg
    return info
    
    v = func('alex')
    v1 = v()
    print(v1)
    
  • 6. Write a function that returns a list of poker cards with 52 items, each of which is a tuple.
    For example: [(`Red Heart', 2), (`Grass Flowers', 2),... (`Spade A')]

    lst = [ i for i in range(2,11)]
    lis = ['J','Q','K','A']
    data = lst + lis
    info = ['Red heart','Spade','Plum blossom','Red Fang']
    v =[]
    for line in info:
        for i in data:
            i = tuple((line,i))
            v.append(i)
    
    print(v)
    
  • 7. Write function, pass in n numbers, return dictionary {max': maximum,'min': minimum}

    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. Write functions to calculate the area of graphics.

    The nested function calculates the area of circle, square and rectangle.

    Call the function area('circle', circle radius) to return the area of the circle

    Call the function area('square', side length) to return the area of the square

    Call the function area('rectangle', long, wide) to return the area of the rectangle

    def area(a1,a2,a3=0):
        '''
        //Calculating graphic area
        :param a1: circular
        :param a2: radius/long
        :param a3:wide
        :return:
        '''
        def circular():
            print('Area of a circle: %s'%(3.14*a2*a2,))
    
        def Square():
            print('The area of a square:%d'%(a2*a2,))
    
        def Rectangle():
            print('The area of a rectangle %d'%(a3*a2,))
    
    # Judging the Input Graphics of Yinghu Lake to Call
        if a1 =='circular':
            circular()
        elif a1 =='Square':
            Square()
        else:
            Rectangle()
    
    # User input
    usee_Graphical = input('Please enter the figure to be calculated :')
    if   usee_Graphical == 'circular':
        usee_radius = int(input('The radius of a circle:'))
        area(usee_Graphical,usee_radius)
    
    elif  usee_Graphical == 'Square':
        usee_wide = int(input('Side Length of Square:'))
        area(usee_Graphical,usee_wide)
    
    elif usee_Graphical=='Rectangle':
        usee_long = int(input('Rectangular rectangle:'))
        usee_long_wode = int(input('The width of the rectangle:'))
        area(usee_Graphical,usee_long,usee_long_wode)
    
    
  • 9. Write a function, pass in a parameter n, and return the factorial of n

    def info (arg):
        sum =1
        for i in range(1,arg):
            sum *=i
        return sum
    
    v = info(7)
    print(v)
    
  • 10 Write a decorator, add authentication function for multiple functions (user's account password is from the file), require a successful login once, follow-up functions do not need to enter user name and password again

    dic = {'Account number': 'alex', 'Password': 123, 'Land': False}
    def func(arg):
        def info():         
            if dic['Land'] == True:
                print('already logged')
                arg()
            usee = input('Please enter your account number.:')
            usee_s = int(input('Please input a password:'))
            if usee == dic['Account number'] and usee_s == dic["Password"]:
                print('Successful landing')
                dic['Land']=True
                arg()
            else:
                print('Error in account or password')
        return info
    
    @func
    def inner():
        print('____Welcome to_____')
    
    @func
    def data():
        print('alexnb')
    
    inner()
    data()
    
  • 11. Use map to process the list of strings and turn everyone in the list into sb, for example alex_sb

    name=['alex','wupeiqi','yuanhao','nezha']
    v = map(lambda x :x+'_sb',name)
    for i in v:
        print(i)
    
  • 12. Use the filter function to process the list of numbers and filter out all even numbers in the list.

    age = [1,2,34,4,5,66,]
    
    v = filter(lambda x :x%2==0,age)
    for i in v:
        print(i)
    
  • 13. As follows, the name of each dictionary corresponds to the name of the stock, the number of shares corresponds to the share, and the price of the share corresponds to the price of the stock.

  • Which built-in function calculates the total price of each stock purchased

  • filter out what stocks have a unit price of more than 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. There are lists of li = ['alex','egon','smith','pizza','alen']. Please change the initial letter of the element beginning with the letter "a" to capital letters.

    li = ['name','egon','smith','pizza','aken']
    lst = [i.capitalize() for i in li]
    print(lst)
    
  • There is a file named poetry.txt, which reads as follows. Please delete the third line.
    In the past, people have taken the Yellow Crane Tower, where there is no spare Yellow Crane Tower.
    Yellow cranes are gone forever, and white clouds are empty for thousands of years.
    Qingchuan calendar Hanyang tree, Fangcao Parrot Island.
    Where is the Dusk Home? Yanbo River makes people sad.

    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)
    
  • There is a file named username.txt. The format of the file is as follows. Write a program to determine whether "Alex" exists in the file. If not, add the string "Alex" to the end of the file. Otherwise, it prompts the user that the user already exists.

    def func():
        with open('a.txt',mode='r+',encoding='utf-8')as f:
            for i in f:
                if 'alex' in i.strip():
                    return 'existence'
            f.write('\nalex')
            return 'To write'
    
    
    v = func()
    print(v)
    
  • A file named user_info.txt is formatted as follows. Write a program to delete lines with 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')
      
    • There is a file named user_info.txt. Its content format is as follows. Write a program to change the username with id 100002 to 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')
      
    • Write a decorator that calculates the execution time of each program.

      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\n')
          print('hahaha\n')
      # Print ('haha n') print a few more lines (50) or the time is 0.0
      print(inner())
      
    • What is lambda? What scenarios did you use lambda in?

      lambda Is an anonymous function
      def func(a):
          return a*2
      func(4)
      
      a = lambda x:x*2
      print(a)
      
    • Title: Write a dice-rolling game, requiring users to press the size, the odds are one to one. Requirements: Three dices, each dice value from 1 to 6, shake size, each printing shake out the value of three dices.

      # Title: Write a dice-rolling game, requiring users to press the size, the odds are one to one. Requirements: Three dices, each dice value from 1 to 6, shake size, each printing shake out the value of three dices.
      import random
      print('----Welcome to the dice roll game-----')
      money = int(input('Please enter your principal:'))
      while 1:
          lst = [random.randint(1,7)  for i in range(3)]
          s = sum(lst)
          usee = int(input('Please enter (1 bet big, 2 bet small 0 exit):'))
          if usee =='0':
              break
          usee_money = int(input('How much do you want to deposit?'))
          if usee >=3:
              print('Input error')
          elif usee ==1 and s <20 :
              print('It's a big bet.')
              money -=usee_money
              print('You still have your principal.%d'%money)
          elif usee == 2 and s>20:
              print('It's a big bet.')
              money -= usee_money
              print('You still have your principal.%d' % money)
          else:
              print('Congratulations on your bet')
              money += usee_money
              print('You still have your principal.%d' % money)
          print('This time is%s'%s)
      

Keywords: Python encoding Lambda

Added by wheelbarrow on Tue, 20 Aug 2019 10:53:57 +0300