fb pixel

Introduction to Python

  • Profound Academy

    • Status
      • 1
        Input and Output
      • 2
        Variables and Integer Arithmetic
      • 3
        Conditional Operators
      • 4
        Advanced Conditions - Nesting
      • 5
        Types and Variables
      • 6
      • 7
      • 8
        For Loops
      • 9
        While Loops
      • 10
        continue, break, while...else
      • 11
        String and List methods
      • 12
        Nested Loops
      • 13
        List Comprehension
      • 14
        Tuples and Sets
      • 15
      • 16
      • 17
        Functions 2
      • 18
        Lambda and higher-order functions
      • 19

  • defaultdict

    Python has a very useful set of data structures in one of its modules called collections. One of those data structures is a dictionary with a default value - defaultdict.
    When creating a defaultdict, we can pass a lambda function that would return a default value for missing elements:
    d = defaultdict(lambda: 'This item does not exist')
    d['Anna'] = 10
    d['Bob'] = 9
    print(d['Bob'])  # 9
    print(d[999])    # This item does not exist
    Here Anna and Bob are added to the keys of the dictionary but 999 is not present, so the program prints This item does not exist.
    This is especially useful when dealing with lists as values:
    grades = defaultdict(lambda: [])
    print(grades['Bob'])  # [8, 9]
    print(grades[999])    # []


    Given n matches of football teams and their opponents, you are asked to find out the number of matches each team played.
    The first line of the input contains a single integer n - the number of matches. The next n lines contain dash (-) separated team names that played against each other. The following line contains comma-separated (,) names of the clubs for which the program should print the number of matches played.
    The program should print space-separated numbers of matches for each of the teams requested on the last line of the input.
    3 Real Madrid-Barcelona Chelsea-Manchester United Arsenal-Barcelona Manchester United,Barcelona,Roma
    1 2 0
    To check your solution you need to sign in
    Sign in to continue