avatarFarhad Malik

Summary

The website content presents five Python programming exercises designed to enhance understanding of the language, covering topics from logging with decorators to multi-process error handling and packaging.

Abstract

The article introduces a set of Python exercises aimed at reinforcing and practicing Python programming skills. It follows up on a previous article that explained the key components of Python. The exercises include implementing a calculator class with logging decorators, performing tree traversal using recursion, flattening nested dictionaries, writing multi-process error handling code, and creating a package with multiple modules. Each exercise is intended to test different aspects of Python programming, such as library imports, class and function creation, decorator usage, recursion, data structures, exception handling, logging, and package organization. The author encourages readers to post their answers in the comments and promises to provide solutions in upcoming blog posts.

Opinions

  • The author believes that these exercises will help solidify the readers' understanding of Python concepts beyond memorization.
  • There is an emphasis on the practical application of Python through the use of real-world programming scenarios.
  • The author suggests that there are multiple approaches to solving the proposed exercises, encouraging creative problem-solving.
  • The article implies that the exercises are suitable for intermediate Python programmers looking to advance their skills.
  • By inviting readers to post their answers, the author fosters a sense of community and collaborative learning.
  • The mention of unit testing and performance profiling indicates the author's opinion on the importance of these practices in software development.

5 Python Exercises

Best Way To Strengthen And Practice Your Python Skills

Recently, I posted an article that aimed to explain the key components of Python programming language.

I received a number of messages whereby the readers asked me to post Python exercises. I wanted to post exercises that should really help one understand how Python works. After thinking about it for some time, I have come up with 5 questions which should test your Python knowledge.

Please have a go and post your answers in the comments sections.

I want to ensure I can help you solidify your understanding of the concepts better rather than giving you questions that we can simply memorize and answer.

Here are 5 Python exercises.

For each exercise, I will also mention the topics it is intending to test. By the end of the exercise, you will feel that you have gained a much superior end-to-end understanding of the language.

Remember, there are multiple ways to peel an orange so solve the questions how you understand them. I will post the answers in an upcoming blog soon.

Photo by bruce mars on Unsplash

1. Logging Using Python Decorator

  1. Implement a calculator class with following functions:

Sum(a,b), Multiply(a,b), Divide(a,b) and Subtract(a,b)

2. Import logging library

3. Decorate each method of the calculator class with a custom method that logs the values of a and b. Implement the logger custom method too.

4. Execute calculator.Sum(a,b) and it should print out the values of a and b. For example:

The Input Values Of A and B Are '123' and '234' # if a =123 and b=234

What Will It Test?

  • It will test whether you understood Pip commands that are required to import the libraries
  • How to create class and functions with arguments in Python
  • How to use decorators

2. Tree Traversal Using Python Recursion

  1. Implement a class: Node which will be used to represent a tree. For example:
class Node(object):
    def __init__(self, name):
        self.name= name
        self.children = []
 def add_child(self, obj):
        self.children.append(obj)

Each node has a name and children e.g.

a = Node('A')
a_goal = Node('Goal')
a.add_child(a_goal)

2. Print out all of the paths of the tree which can lead you to the node named “Goal”.

3. The tree can have N number of levels (1>N>100). Goal node can have children too.

For example, for tree below, your code should print out following paths:

A->Goal

A->B->Goal

A->D->Goal

A->F->H->L->Goal

All other paths do not lead you to the Goal node.

Write your code in a way that it can be unit tested.

What Will It Test?

  • It should test your understanding of recursion
  • It should also test how you prevent from going into infinite loops — it will test your loops, expression and conditional logic
  • It will also test your data structures understanding and variables scope
Photo by Fabrizio Verrecchia on Unsplash

3. Flatten A List Of Nested Dictionaries Into A List Of Multiple Flattened Dictionaries

  1. Create an object which contains a list of dictionaries.
  2. Each item in the list is a dictionary which contains a number of keys.
  3. Each key of the dictionary will contain a value. The value can be of type string, or it can be a of type dictionary. When the value is of type dictionary then it implies that it is a nested dictionary within a dictionary.
  4. Each dictionary can contain a variable number of keys.
  5. Loop over the items and create a single dictionary to store keys at the same level. For example, if you loop over the items and if each item contains a dictionary with two keys e.g.“Name” and “Surname” and both of the keys contain values of type string then simply return the collection of dictionaries (as it’s already flat).
  6. However if it contains “Name”, “Surname” and “PlacesVisited” keys, where PlacesVisited is itself a list of dictionaries such that each item of the dictionary contains two keys “Name of place” and “date when it was visited” then I expect to see two lists as the result. First list should contain a collection of dictionaries with keys Name and Surname. The second list should contain the keys “Name Of place”, “date when it was visited” and ParentId where ParentId will contain the key “Name” of the first dictionary.
  7. Take the value of the ParentId as the value of the first key of the parent dictionary e.g. for the example above, “Name” is chosen as the ParentId.

For each nested dictionary, create a new dictionary.

Final result should be a number of flatten dictionaries to represent a nested dictionary

For example, if this is your input:

sample_object = [
{'Name':'Farhad', 'Surname:'Malik', 'Blogs':{'BlogName:'Python1','Date1':'20180901'}},
{'Name':'Farhad2', 'Surname:'Malik2', 'Blogs':{'BlogName:'Python3','Date1':'20180101'}}
]
The result should be:
dictionary_1 = [
{'Name':'Farhad', 'Surname:'Malik'}, 
{'Name':'Farhad2', 'Surname:'Malik2'}
]
dictionary_2 = [
{'ParentId':'Farhad', 'BlogName:'Python1','Date1':'20180901'},
{'ParentId':'Farhad2','BlogName:'Python3','Date1':'20180101'}
]

The key is to ensure that the items at the same level belong to the same dictionary.

What Will It Test?

  • It should test your understanding of dictionaries, arrays and sets.
  • It should also help you understand how to check for keys and values
  • Lastly, it will help you see how you can pass in optional parameters.
  • This is how you can flatten out a JSON object.
Photo by Kaleidico on Unsplash

4. Multi-Process And Error Handling Code

  • Take the three exercises above, make the code run on multiple processes
  • Use try/catch and catch exceptions where appropriate
  • Profile and log performance of the code
  • Write unit tests for each of the exercises that perform positive and negative tests

What Will It Test?

  • This will really help you see how to run your code on multiple processes
  • How to catch exceptions and how to enable logging in your code to an extent that it is useful.

5. Package And Modules

  • Create the classes and code that you have implemented above into a package with multiple modules
  • Understand how the files should be placed and imported.
  • Create a main class that drives everything
  • Write out a console application that runs your unit tests via command line and informs you the tests that have passed or failed.

What Will It Test?

  • It should help you really understand and see how packages and modules work
  • You will get a solid understanding of Python programming language

Summary

This article presented you with 5 Python exercises.

Please post your answers in the comments section. I will post the answers in my upcoming Python blogs.

If you want more exercises, please do let me know.

Python
Programming Languages
Technology
Fintech
Data Science
Recommended from ReadMedium